Skip to content

Latest commit

 

History

History
53 lines (37 loc) · 1.24 KB

File metadata and controls

53 lines (37 loc) · 1.24 KB

Wrapper Class

Boxing and Unboxing, AutoBoxing


Intro

In Java, there are primitive data types and Wrapper classes

  • Primitive data types: int, long, float, double, boolean, etc.
  • Wrapper classes: Integer, Long, Float, Double, Boolean, etc.

Boxing & Unboxing

  • Boxing

    • Converting a Primitive data type to a Wrapper class

      int n = 100;
      Integer num = new Integer(n);
  • Unboxing

    • Converting a Wrapper class to a Primitive data type

      Integer num = new Integer(100);
      int n = num.intValue();

Auto Boxing

  • Since JDK 1.5, the Java compiler automatically performs conversion when boxing and unboxing are needed -> Auto Boxing & Auto Unboxing

    • This feature is only available when there is a corresponding Primitive data type for each Wrapper class

      // Auto Boxing
      int n = 100;
      Integer num = n;
      
      // Auto Unboxing
      Integer num = new Integer(100);
      int n = num;
  • Caution: Performance

    • Although Auto Boxing and Auto Unboxing are provided for convenience, since additional computation work is needed internally, it is better to implement same-type operations so that Auto Boxing & Auto Unboxing does not occur