Java 5: Autoboxing and unboxing

  Java Features     Java 5     Java 7     Java 8  
Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

The Conversion between the primitive data types and their corresponding object wrappers directly is a new feature in Java 5. The conversion from primitive data types to their object wrappers is called autoboxing, but converting of the other way around is called unboxing.

For more info click here to read Oracle’s explanation.

Example 1: Autoboxing and unboxing code

What is the output of the following code?

public class MyClass
  public static void main(String[] args)
    // before Java 5
    int i = 8;
    Integer intOb = Integer.valueOf(i);
    int primVar = intOb.intValue();
    /* after java 5 autobxing, convert
     * primitive variable to wrapper
    Integer intOb2 = i;
    /* unboxing convert object 
     * to primitive variable
    int primVar2 = intOb2;
Author: Sar Maroof

Answer explanation

The correct answer is: 88.

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply