자바의 정석 - 기초편

상수와 리터럴

ODaram 2022. 7. 26. 17:21

 > 변수 (variable) - 하나의 값을 저장하기 위한 공간 (다른 값으로 몇번이고 바꿀 수 있음)

 > 상수 (constant) - 한 번만 값을 저장 가능한 변수 (한 번 저장하면 다른 것으로 바꿀 수 없음)

 > 리터럴 (literal) - 그 자체로 값을 의미하는 것 (= 기존의 상수) 

  

    int score = 100;

    int score = 200;

            ·

            ·

            ·

    fimal int MAX = 100; // MAX 는 상수 

                 MAX = 200; // 에러

 

    char ch = 'A';

    String str = "abc";

 

예제)

 1. 변수 score 값 출력 : 100 

public class VarEx3 {
	public static void main(String[] args) {
    	int score = 100;
        System.out.println(score);    
	}
}

2. 변수 socre 값 출력 : 200

public class VarEx3 {
	public static void main(String[] args) {
    	int score = 100;
        score = 200;
        System.out.println(score);    
	}
}

3. score을 상수로 만들기

public class VarEx3 {
	public static void main(String[] args) {
    	final nt score = 100;
        socre = 200; // 오류 발생
        System.out.println(score);    
	}
}

> problems 에 자세하게 설명됨

problems 오류 설명

4. 상수를 지정해줄 때는 꼭 초기화를 시켜줘야함

public class VarEx3 {
	public static void main(String[] args) {
    	final nt score; // = 100;
        System.out.println(score); // 오류 발생, socre 값 출력 불가
	}
}