[JAVA] 원시 타입(Primitive Types)과 참조 타입(Reference Types), 제네릭 타입(Generic Type)

뽕칠이·2024년 1월 8일
0

원시 타입(Primitive Types)

  • byte, short, int, long, float, double, boolean, char 8가지 타입이 해당되며 객체가 아닌 실제 데이터 값을 저장한다.
데이터 타입메모리 크기최솟값최댓값기본값
byte1byte-1281270
short2byte-32,76832,7670
int4byte-2**31 또는 02**31-1 또는 (2**32)-10
long8byte-2**62 또는 02**62-1또는 (2**63)-10L
float8byte-3.4E383.4E380.0F
double8byte-1.7E3081.7E3080.0
boolean1bytefalsetruefalse
char2byte(유니코드)'\u000'(0)'\ufff'(65,535)'\u000'

참조 타입(Reference Types)

  • 객체를 참조(주소를 저장하는 타입으로 메모리 주소 값을 통해서 객체를 참조한다.
  • 원시 타입을 제외한 타입들(문자열, 배열, 열거, 클래스, 인터페이스)을 말한다.
  • 자바에서 데이터 타입과 힙 메모리에 저장된 객체 접근하기 위한 일종의 포인터스택 메모리에 저장되며, 객체힙 메모리에 저장한다. 객체를 사용할 때마다 참조 변수에 저장된 객체의 주소를 불러와 사용하는 방식이다.
스택 메모리힙 메모리
Value TypesReference Types
Pointers to the Reference Type

원시 타입과 참조 타입의 차이

  1. null을 담을 수 있는가?
  • 원시 타입은 null을 담을 수 없지만, 참조 타입은 null을 입력값으로 받을 수 있다.
  1. 제네릭 타입에서 사용할 수 있는가?
  • 원시 타입은 제네릭 타입에서 사용할 수 없지만, 참조 타입은 제네릭 타입에서 사용할 수 있다.

제네릭 타입(Generic Type)

제네릭 타입(Generic Type)이란?

  • 데이터 형식에 의존하지 않고 하나의 값이 여러 다른 데이터 타입을 가질 수 있도록 하는 방법이다.
  • 클래스 내부에서 사용할 데이터 타입을 외부에서 지정하는 기법

제네릭 타입의 특징
제네릭 타입에는 참조 타입만 할당 받을 수 있다. 이 때 int, double과 같은 원시 타입을 제네릭 타입 매개변수로 사용할 수 없으므로 이를 대체할 수 있는 Integer, Double 과 같은 Wrapper 클래스를 사용한다.

기본적인 제네릭 타입 선언

class Person<T> {
	public T info;
}

public class GenericDemo {
	public static void main(String[] args) {
    	Person<String> p1 = new Person<String>();
        Person<StringBuilder> p2 = new Person<StringBuilder>();
    }
}

복수 제네릭 타입, Wrapper 클래스 사용

class EmployeeInfo {
	public int rank;
    Employee(int rank) {this.rank = rank};
}

class Person<T, S> {
	public T info;
    public S id;
    Person(T info, S id) {
    	this.info = info;
        this.id = id;
    }
}

class GenericDemo {
	public static void main(String[] args) {
    	EmployeeInfo emp = new EmployeeInfo(1);
    	Integer id = new Integer(10);
        Person p1 = new Person(emp, id);
        // Person<EmployeeInfo, Integer> p1 = new Person<EmployeeInfo, Integer>(emp, id);
    }
}

0개의 댓글