on
1013 - 형변환(Type Casting)
1013 - 형변환(Type Casting)
형변환이란 특정 데이터타입의 값을 다른 데이터타입으로 바꾸는 것을 말한다.
형변환에는 [암시적 형변환]과 [명시적 형변환]이 있다.
[암시적 형변환(implicit type casting)]
우리가 특별히 명령어를 적어주지 않아도 자바가 내부적으로 알아서 데이터타입을 바꿔주는 것
작은 데이터타입을 더 큰 데이터 타입으로 바꾸거나 정수를 실수로 바꿀 때 발생
[명시적 형변환(explicit type casting)]
우리가 명확하게 명령어를 적어주어야 형변환이 발생된다.
만약 우리가 명령어를 적어주지 않는다면 에러가 발생
더 큰 데이터 타입을 작은 데이터 타입으로 바꾸거나 실수를 정수로 바꿀 때 해줘야한다.
명시적 형변환을 하는 방법 : (바꿀 데이터타입) 바꿀 값;
public class Ex03TypeCasting { public static void main(String[] args) { System.out.println("암시적 형변환"); // byte 변수 byByte 선언 후 30 저장 byte myByte = 30 ; // int 변수 myInt 선언 int myInt ; // myInt에 myByte의 현재 값을 저장 myInt = myByte; // myInt를 화면에 출력 System.out.println("myInt : " + myInt); System.out.println("---------------------------"); System.out.println("명시적 형변환"); // myInt에 50 저장 myInt = 50 ; // myByte에 myInt의 현재값을 저장해보자 // myByte = myInt; // 에러 발생!!!! -> 형변환를 해줘야한다. myByte = (byte)myInt; // 화면에 myByte값 출력 System.out.println("myByte : " + myByte); System.out.println("---------------------------"); System.out.println("overflow 일 때"); myByte = 126 ; System.out.println(myByte); myByte = 127 ; System.out.println(myByte); // 128부턴 byte의 범위를 넘어가서 에러가 나기 때문에 // 명시적 초기화를 해줘야한다. // 하지만 값은 overflow가 일어나기 때문에 정확하게 나오지 않는다. myByte = (byte)128 ; // 127+1 -> -128 System.out.println(myByte); myByte = (byte)129 ; // -128+1 -> -127 System.out.println(myByte); System.out.println("---------------------------"); System.out.println("underflow 일 때 "); myByte = -127; System.out.println(myByte); myByte = -128; System.out.println(myByte); // -129부턴 byte의 범위를 넘어가서 에러가 나기 때문에 // 명시적 초기화를 해줘야한다. // 하지만 값은 overflow가 일어나기 때문에 정확하게 나오지 않는다. myByte = (byte)-129; System.out.println(myByte); myByte = (byte)-130; System.out.println(myByte); System.out.println("---------------------------"); System.out.println("over,underflow 발생 시 더 큰 타입으로 형변환할 때"); // 원래 값으로 돌아가지 않는다. 이미 myByte엔 그 값이 저장되어있기 때문에 myByte = (byte)300; myInt = myByte ; System.out.println(myInt); } }
암시적 형변환 myInt : 30 --------------------------- 명시적 형변환 myByte : 50 --------------------------- overflow 일 때 126 127 -128 -127 --------------------------- underflow 일 때 -127 -128 127 126 --------------------------- over,underflow 발생 시 더 큰 타입으로 형변환할 때 44
from http://helloenavy.tistory.com/14 by ccl(A) rewrite - 2021-10-17 23:28:01