Java 5: Autoboxing and unboxing

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;
    System.out.print(intOb2);
    System.out.print(primVar2);
  }
}
Author: Sar Maroof

Answer explanation

The correct answer is: 88.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017