코딩/Java

자바(JAVA) - 변수 선언, 데이터 타입

숲속의 움비 2021. 1. 23. 23:00
반응형

변수 만들기

public class example1 {
	public static void main(String[] args) {
		/*
		 * 		여러줄 주석
		 */
		int x;			// 변수 x 선언
		x = 1;			// 변수 x를 초기화(최초 값을 저장)
		int y = 2;		// 변수 선언과 초기화를 함께
		int result = x + y;
		System.out.println(result);
	}
}

 - 변수 : 값을 저장할 수 있도록 메모리 영역에 붙인 이름

           변수를 통해 프로그램은 값을 저장하고 읽을 수 있다.

 - 변수 선언 : 변수의 타입과 이름을 결정해 변수를 만들도록 명령

 - 변수의 이름 규칙

    첫 문자는 영문자나 '_', '&' (한글 가능)

    글자 수에 제한이 없으며 공백 문자 및 특수문자 사용불가

    이름에 영문자의 대문자와 소문자는 구별된다.

    자바 예약어를 이름으로 사용할 수 없다.

 

 - 자바의 예약어

abstract boolean break byte case catch catch char continue
default do double else extends false fianl float for
implements instanceof int interface long native new null package
protected public return static super switch this throw throws
transient true try void while if synchronized    

1. 변수의 초기화

public class example2 {
	public static void main(String[] args) {
		int value;
		int result = value + 10;
	}
}

 - 변수를 초기화하지 않음 -> The local varible value may not have been initialized 오류

 

2. 변수 사용

public class example3 {
	public static void main(String[] args) {
		LocalDate date = LocalDate.now();
		int year = date.getYear();
		int month = date.getMonthValue();
		int day = date.getDayOfMonth();
		System.out.println(year + "년" + month + "월" + day + "일");
	}

출력된 값 : 2021년 1월 23일

 

3. 변수 사용 범위 (scope)

public class example4 {
	public static void main(String[] args) {
		int v1 = 15;
		if(v1>10) {
			int v2 = v1 - 10;
		}
		int v3 = v1 + v2 + 5;
	}
}

 - 변수의 사용 범위 (scope)

    (오류)v2 cannot be resolved to a variable

    변수는 변수가 선언된 중괄호 내부에서만 사용할 수 있다.

    메소드 전체에서 사용하고 싶다면 메소드 중괄호 첫머리에 선언한다.

 

자바의 데이터 타입

 - 기본 타입 : 정수, 실수, 참/ 거짓 값을 저장하는 변수

값의 종류 타입 크기 범위
정수 byte 1 8bit (-128~127)
short 2 16bit (-32768 ~ 32767)
int 4 32bit (-2147483648 ~ 2147483647)
long 8 64bit (-922경 ~ 922경)
문자 char 2 16bit (0 ~ 65535)
실수 float 4 32bit
double 8 64bit
논리 boolean 1 true, false

프로그래밍에서 값을 메모리에 할당할 때 변수 영역이 메모리를 무한대로 사용하게 할 수는 없다.

2byte 크기의 데이터를 저장하기 위해서 굳이 4byte의 변수 영역을 할당받을 필요는 없는 것이다.

자바에서 변수를 사용할 때 적당한 크기와 적당한 데이터 형태로 메모리를 할당받게 하여 메모리 사용의 효율성을 보장하도록 제공되는 것이 데이터 타입이다.

 - 참조 타입 : 객체를 가리키는 리모컨에 해당하며 크기는 4byte

반응형