3. What is the autoboxing and unboxing ?

toutbon·2024년 2월 20일
0

질문의 목적

JDK 1.5 부터 적용된 autoboxingunboxing에 대해 묻는 문항

Primitive vs Wrapper Class

  • 자바에는 크게 두 가지의 데이터 타입이 있다 : primitive, object
  1. primitive data type
    가볍다. stack 메모리에 저장된다.
    boolean, char, short, int, long, float, double
  2. objective data type
    상대적으로 무거운 데이터. 실제 데이터는 heap 메모리에 존재하고 데이터를 가리키는 레퍼런스만 stack 메모리에 존재한다.
  • JDK 1.5 이전에는 primitive type과 object type이 서로 호환이 되지 않았기 때문에 primitive type을 object type으로 만들기 위해 Wrapper class 가 있었다
  • Wrapper Class 예시 : Boolean, Character, Byte, Short, Integer, Long, Float, Double

Autoboxing 과 Unboxing

  • Autoboxing : from primitive type to wrapper class
    - primitive type을 컴파일 할 때 Integer 객체로 변환 해줌
    		// JDK 1.5 이전 버전 
    		int a = 2017;
    		Integer b = new Integer(a);
    	
    		// JDK 1.5 이후 버전 
    		int a = 2017;
    		Integer b = a; 
    	
  • Unboxing : from wrapper class to primitive type
    - wrapper class을 컴파일 할 때 privitive type으로 변환 해줌
    		// JDK 1.5 이전 버전 
    		Integer a = new Integer(2017);
    		int b = a.intValue()
    	
    		// JDK 1.5 이후 버전 
    		Integer a = new Integer(2017);
    		int b = a;
    	

KeyWord 정리

  • autoboxing : compiler automatically converts primitive to wrapper object
  • unboxing : compiler automatically converts wrapper to primitive data
  • let developers write cleaner code, make it easier to read
    |-> 개발자는 깔끔하고 읽기 쉬운 코드를 작성할 수 있다.
profile
뚜봉

0개의 댓글