본문 바로가기
자바공부/변수와 타입

JAVA(자바)-타입 변환 중에 자동 타입 변환

by You진 2020. 12. 4.

타입 변환

 -데이터 타입을 다른 타입으로 변환

  (예 byte <-> int, int <-> double)

 -종류

  자동(묵시적)타입 변환 : Promotion

  강제(명시적)타입 변환 : Casting

 

자동 타입 변환

 - 프로그램 실행 도중에 작은 타입은 큰 타입으로 자동 타입 변환됨

   작은크기 타입 -> 큰 크기타입 (예 byte(1) -> int(4) )

   ★byte(1) < short(2) < int(4) < long(8) < float(4) < double(8)

   float는 4byte인데 int와 long보다 큰 타입으로 표시가 된다. 그 이유는 값의 표현이 더 크기 때문이다

public class PromotionExample {
	public static void main(String[] args) {
		byte byteValue = 10;
		int intValue = byteValue;		//byte -> int
		System.out.println(intValue);
		
		char charValue ='가';
		intValue = charValue;			//char -> int
		System.out.println("가의 유니코드= "+ intValue);
		
		intValue = 500;
		long longValue = intValue;		//int -> long
		System.out.println(longValue);
		
		intValue = 400;
		float floatValue = intValue;		//int -> float
		System.out.println(floatValue);
		
		intValue = 200;
		double doubleValue = intValue;		//int -> double
		System.out.println(doubleValue);
	}
}

 

연산식에서 자동 타입 변환

연산은 같은 타입의 피연산자간에만 수행

 - 서로 다른 타입의 피연산자는 같은 타입으로 변환됨 ( 크기가 큰 타입으로 자동 변환)

 - 자바 정수 연산일 경우 int 타입을 기본으로 한다.( 피연산자를 4byte 단위로 저장하기때문)

 - int 이하의 타입 연산는 int reslut = (byte,char,short,int 타입)   연산자(+,-,*,/,%)   (byte,char,short,int 타입)

 - long 타입 연산 long result = long 변수 연산자(+,-,*,/,%)   (byte,char,short,int 타입)

 - float 연산 : 두 피연산자가 모두 float 일 경우에만 float result = (float타입)  연산자(+,-,*,/,%)  (float타입)

 - 실수 리터럴 및 double 연산 long result = long 변수 연산자(+,-,*,/,%)   (byte,char,short,int,float,double 타입)

		byte byteValue1 = 10;
		byte byteValue2 = 20;
		int intValue1 = byteValue1 + byteValue2;
		System.out.println(intValue1);
		
		char charValue2 = 'A';
		char charValue3 = 1;
		int intValue2 = charValue2 + charValue3;
		System.out.println(intValue2);

		int intValue3 = 10;
		int intValue4 = intValue3 / 4;
		System.out.println(intValue4);

		int intValue5 = 10;
		double doubleValue1 = intValue5 / 4.0;
		System.out.println(doubleValue1);
		
		int intValue = 10;
		double doubleValue = 5.5;
		double result = intValue + doubleValue;
		System.out.println(result);
		
		long longValue1 = 10;
		int intValue6 = 5;
		long result4 = longValue1 + intValue6;
		System.out.println(result4);
		
		float floatValue1 = 2.5F;
		double doubleValue2 = 2.5;
		double result5 = floatValue1 + doubleValue2;
		System.out.println(result5);
   
   		float floatValue2 = 10.2f;
		float floatValue3 = floatValue2+5;
		System.out.println(floatValue3);
        
        	//intValue1 => 30
        	//intValue2 => 66
        	//intValue4 => 2
        	//doubleValue1 => 2.5
        	//result1 => 15.5
        	//result2 => 15
        	//reslut3 => 5.0
          	//floatValue3 => 15.2

 

 

'자바공부 > 변수와 타입' 카테고리의 다른 글

JAVA(자바)-타입 변환 중에 강제 타입 변환  (2) 2020.12.10
JAVA(자바)-데이터 타입  (0) 2020.11.29
JAVA(자바)-리터럴(literal)  (0) 2020.11.28
JAVA(자바)-변수  (0) 2020.11.27