x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Autoboxing and unboxing in Java

    Before Java 5, Wrapper classes like Integer, Float, Boolean, etc were used to put primitives into collections and also to get it back from a collection. First you had to wrap a primitive before you could put it into a collection.

    With Java 5, Autoboxing automatically converts primitive into Wrapper obejct and while unboxing converts back primitive from Wrapper object. When the primitive is automatically converted into a Wrapper, it is called Autoboxing while when the value is converted automatically from wrapper to a primitive, it is called unboxing. Below are the Autoboxing and unboxing examples.

    Autoboxing and unboxing Examples

    Example 1:

    import java.util.*;
    public class Test { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(new Integer(10)); // Pre Java 5 // autoboxing, no need to wrap int value in Integer object list.add(10); // Post Java 5 } }

    Example 2:

    public class Test {
        public static void main(String[] args) {
            Integer i = new Integer(100); 
            int j = i; // unboxing 
            System.out.println(j);  // prints 100 
        }
    }		

    Example 3:

    public class Test {
        public static void main(String[] args) {
            Integer i = 100; // autoboxing
            i++; // unboxing  
            System.out.println(i);  // prints 101 
        }
    }		

    Example 4:

    public class Test {
        public static void main(String[] args) {
            Integer num = new Integer(5); 
            int i = num; // unboxing  
        }
    }		

    Example 5:

    When we use == operator to compare two wrapper objects, then the objects are first converted to their primitive value or unboxed first.

    public class Test {
        public static void main(String[] args) {
            Integer num1 = 50;
            Integer num2 = 50;
            System.out.println(num1 == num2); // prints true , used unboxing
            System.out.println(num1 != num2); // prints false
            System.out.println(num1.equals(num2)); // prints true
        }
    }		

    References : https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
    Comments

    Leave a Reply

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











    Share This