자바의 신 - 기본 정수 자료형(데이터)들의 범위

Yumin Jung·2023년 11월 5일
0

자바의 신

목록 보기
2/4
public class PrimitiveTypes{
    public static void main(String []args){
        PrimitiveTypes types = new PrimitiveTypes();
        types.checkByte();
        types.checkOtherTypes();
    }
    public void checkByte(){
        byte byteMin=-128;
        byte byteMax=127;
        System.out.println("byteMin="+byteMin);
        System.out.println("byteMax="+byteMax);
        byteMin=(byte)(byteMin-1);
        byteMax=(byte)(byteMax+1);
        System.out.println("byteMin-1="+byteMin);
        System.out.println("byteMax+1="+byteMax);
    }

    public void checkOtherTypes(){
        short shortMax=32767;
        int intMax=2147483647;
        long longMax=9223372036854775807L;
        shortMax=(short)(shortMax+1);
        intMax=(int)(intMax+1);
        longMax=(long)(longMax+1);
        System.out.println("shortMax+1="+shortMax);
        System.out.println("intMax+1="+intMax);
        System.out.println("longMax+1="+longMax);
    }
}

이 코드는 기본 데이터 유형(primitive types)에 대한 정보를 보여주고, 해당 데이터 유형의 범위를 초과하는 경우 어떻게 동작하는지를 보여주는 Java 프로그램이다.

미리보는 결론

Java에서 데이터 유형을 오버플로우시키면 최소값에서 최대값 또는 최대값에서 최소값으로 루프된다.

checkByte ( )

byte 데이터 유형은 8비트를 사용하며, 범위는 -128부터 127까지이다.

byteMin은 -1을 더하면 최소값보다 더 작은 값을 가지게 된다.
byteMin은 127로 바뀐다.

byteMax는 1을 더하면 최대값보다 더 큰 값을 가지게 된다. 이 경우, byteMax는 -128로 바뀐다.

checkOtherTypes ( )

shortMax는 최대값인 32767에서 1을 더하면 오버플로우되어 최소값인 -32768이 된다.

intMax는 최대값인 2147483647에서 1을 더하면 오버플로우되어 최소값인 -2147483648이 된다.

longMax는 최대값인 9223372036854775807에서 1을 더하면 오버플로우되어 최소값인 -9223372036854775808이 된다. L을 사용하여 long 데이터 유형임을 나타냈다.

결론

결론적으로, Java의 기본 데이터 유형은 정해진 범위를 가지며, 범위를 초과하면 데이터가 루프될 수 있음을 보여주는 예제 코드이다. 이러한 동작을 이해하고 주의하는 것이 중요하다.

profile
문과를 정말로 존중해

0개의 댓글