[자바] Primitive 데이터 타입 알아보기

1. bit (비트)

  • 데이터의 값을 나타내는 가장 작은 단위
  • 0이나 1 둘 중에 하나의 값만 가질 수 있다
  • 비트들이 모여 더 큰 수나 값을 표현할 수 있다
  • 8개의 비트가 모인걸 byte(바이트)라고 한다
  • 예로 숫자 3은 이진법(0과 1만을 이용하는 수 체계)으로 0011로 표현이 가능하다


2. Primitive 데이터 타입

자바엔 8개의 Primitive(원시적인, 원초적인) 데이터 타입이 있다. 그룹별로 묶어서 보자.

Integer (정수)

  • byte: 8비트
  • short: 16비트
  • int: 32비트
  • long: 64비트

Floating point (부동 소수점?)

  • float: 32비트
  • double: 64비트

그 외

  • char: 16비트
  • boolean: true/false

케바케이지만 이중에 제일 많이 쓰는 데이터 타입은 int, long, boolean 정도가 되겠다. 물론 기능에 따라 나머지 타입들도 필요할 때가 있다. 

숫자 타입의 경우 맨 앞에 비트는 sign bit으로 활용된다. 때문에 8비트로 표현 가능한 수는 2^8 = 256이 아닌 2^8 - 1 = 255이다. 그래서 byte으로 표현 가능한 수의 범위는 -128부터 127까지다.

예제
public class Main {
public static void main(String[] args) {
byte a = 10;
short b = 10;
int c = 10;
long d = 10;

System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("c=" + c);
System.out.println("d=" + d);
}
}
결과
a=10
b=10
c=10
d=10


3. 형 변환

같은 그룹의 데이터 타입은 형 변환이 가능하다. 예로 int를 long으로, long을 short로 등.

더 큰 비트를 가진 데이터 타입으로 변환하면 widening casting, 더 작은 데이터 타입으로 변환하면 narrowing casting이라 한다. widening은 자동으로 변환되고 narrowing은 변환하고자 하는 타입을 명시해주어야 한다. 또한 변환 과정에서 narrowing은 큰 그릇에 있던 정보를 작은 그릇에 넣어야 하기 때문에 비트 손실이 일어날 수도 있다.

예제
public class Main {
public static void main(String[] args) {
byte a = 10;
short b = a; //widening casting

long aa = Integer.MAX_VALUE + 1;
int bb = (int) aa;

System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("aa=" + aa);
System.out.println("bb=" + bb);
}
}
결과
a=10
b=10
aa=9223372036854775807
bb=-1


4. Wrapper classes

Primitive 데이터 타입을 한번 감싼 클래스다. 모든 타입마다 해당하는 wrapper 클래스가 있고 이 클래스들의 존재 이유는 Collection interface가 primitive를 지원하지 않기 때문이다. 

예제
public class Main {
public static void main(String[] args) {
Byte a = Byte.valueOf((byte) 10);
Short b = Short.valueOf((short) 10);
Integer c = Integer.valueOf(10);
Long d = Long.valueOf(10L);

System.out.println("a=" + a.byteValue());
System.out.println("b=" + b.shortValue());
System.out.println("c=" + c.intValue());
System.out.println("d=" + d.longValue());
}
}
결과
a=10
b=10
c=10
d=10