Thursday, December 18, 2014

Autoboxing and Unboxing in Java



Autoboxing means conversion of java premitives to their corresponding wrapper object class, it happens automatically by the java compiler.
For example int to Integer, double to Double.

Unboxing is quite opposite to the autoboxing means java wrapper objects are automatically converts to their premiteves by compiler.
For example Integer to int, Boolean to boolean,Double to double.

See the below written code snap
Autoboxing
a.       int x=100;
                     Integer int_val=x;
b.     double amount=10.50;
  Double amount_val=amount;
Unboxing
a.       Integer int_val=new Integer(100);
 int score=int_val;
b.    Double amount=new Double(100.50);
                    double total_amount=amount;

Using this java feature we can  also assign any value to the super class Object.
For example you can write code as follows using Autoboxing.

        Object x=1;
       Object name="Singh";
       System.out.println(x);
       System.out.println(name);

The above code will run successfully.
 This feature was introduced in Java 5 realease in September 2004.

No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...