Java

[Java] Primitive Type & Reference Type

pseudocoder_ 2024. 1. 25. 17:40
728x90

자바에는 데이터의 타입을 나눌 때 Primitive Type(원시 타입), Reference Type(참조 타입) 두 가지 타입으로 나눌 수 있다. 

 

 

Primitive Type

메모리에 실제 값을 저장하는 변수이다. Primitive Type은 8가지 종류의 데이터 타입으로 나뉜다.

  1. boolean
  2. byte
  3. short
  4. char
  5. int
  6. long
  7. float
  8. double

 

Reference Type

메모리에 참조 객체의 주소값을 저장하는 변수이다.

Reference Type은 8가지 종류의 Primitive Type을 제외한 모든 데이터 타입이다. 인스턴스화가 가능한 클래스나 배열이 Reference Type에 포함된다. 아래와 같은 우리에게 익숙한 예시가 있다.

  1. String
  2. Scanner
  3. int[]
  4. String[]

 

Primitive Type과 Reference Type 간의 차이점

가장 큰 차이점은 Primitive Type은 데이터의 실제 값을 저장하고, Reference Type은 데이터의 주소값을 heap영역에 저장한다는 것이다. 

 

1. Null값 할당

Primitive Type은 null값을 가질 수 없으나, Reference Type은 null값을 가질 수 있다. 

Primitive Type의 boolean은 false 값 / byte, short, char, int, long 값은 0을 기본값으로 지닌다.

반면 Reference Type은 null값을 가지는 것이 가능하다.

String s1 = null;
System.out.println(s1); // null

int a = null;
System.out.println(a); // 에러 발생

 

2. 데이터 할당

Primitive Type은 데이터에 값을 할당하면 데이터 그 자체가 할당되지만 Reference Type에 할당을 하면 해당 객체의 주소값이 할당이 된다. 

int i = 20;
int j = i;
j++; // 값 자체를 할당해준 Primitive Type이기 때문에 j = 21, i = 20이다.

System.out.printf("value of i and j after modification i: %d, j:
 %d %n", i, j);

List<String> list = new ArrayList(2);
List<String> copy = list;  

copy.add("EUR"); // 주소값을 할당한 Reference Type이기 때문에 copy와 list 모두 변경사항이 적용된다.
System.out.printf("value of list and copy after modification list: %s,
 copy: %s %n", list, copy);

결과 :
value of i and j after modification i: 20, j: 21 
value of list and copy after modification list: [EUR], copy: [EUR]

 

 

3. 동일 데이터 비교

Primitive Type의 경우 == 연산자로 비교가 가능하지만, Reference Type은 데이터의 주소값을 기준으로 비교를 하기 때문에 같은 데이터값을 가진 변수라도 서로 다른 데이터로 인식된다. String의 경우 값을 비교하기 위해 == 대신 .equals과 같은 특수 연산자를 사용한다. 

 

아래 예시의 s3처럼 s2의 주소값을 복사받아 변수를 할당한 경우에는 같은 데이터로 인식되기 때문에 == 연산자를 사용해도 문제가 없다.

// Primitive Type
int a = 100;
int b = 100;

System.out.println(a == b); // true

// Reference Type
String s1 = new String("java");
String s2 = new String("java");
String s3 = s2;

System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // true
System.out.println(s1.equals(s2)); // true

 

 

4. 성능 비교

한 줄로 요약한다면 Primitive Type을 사용하는 것이 Reference Type을 사용하는 것보다 작업 처리 속도 측면에서 더 빠르다.

Primitive Type은 스택 메모리에 존재하는 실제 값을 불러오기 때문에 메모리 효율성이 높고 액세스 속도가 빠른 반면,

Reference Type은 실제 값을 힙 영역에 저장하고 스택 메모리에는 주소값을 저장한다. 따라서 매번 데이터 액세스를 위해 주소값을 활용한 간접참조 때문에 액세스 속도가 느려지는 것이다.

 

  Primitive Type Reference Type
Null 항상 값을 가지며 Null이 될 수 없다. 기본 변수를 생성할 경우 초기 값은 0이다. Null을 값으로 가질 수 있다. Null인 상태에서는 함수를 호출 시에 NullPointerException이 에러가 발생한다.
데이터 할당 값 자체를 복사하여 변수에 할당한다. 해당 객체의 주소값을 복사하여 변수에 할당한다.
데이터 비교 == 연산자를 활용하여 데이터를 비교한다. == 연산자로 정확한 데이터 비교가 되지 않는다.

 

 

Reference

https://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

 

10 Difference between Primitive and Reference variable in Java - Example Tutorial

A blog about Java, Programming, Algorithms, Data Structure, SQL, Linux, Database, Interview questions, and my personal experience.

javarevisited.blogspot.com

https://gyoogle.dev/blog/computer-language/Java/Primitive%20type%20&%20Reference%20type.html

 

Primitive type & Reference type | 👨🏻‍💻 Tech Interview

Primitive type & Reference type Goal Primitive type에 대해 설명할 수 있다. Reference type에 대해 설명할 수 있다. Abstract 자바에는 기본형(Primitive type)과 참조형(Reference type)이 있습니다. 일반적인 분류는 다음

gyoogle.dev

https://hyperskill.org/learn/step/5035

 

Primitive and reference types

In Java, all data types are separated into two groups: primitive types and reference types. Java pro

hyperskill.org

https://www.baeldung.com/java-primitives-vs-objects

 

728x90