Posts

Showing posts with the label boxing

Java Puzzle – Magic of Auto-boxing

  Auto-boxing is introduced in JDK 5.0.  it converts primitive data variable to corresponding wrapper classes and vice versa without any explicit efforts. For example int to Integer and Integer to int . Here is the one program using auto-boxing feature 1: class AutoBoxingTest 2: { 3: public static void main(String[] args) 4: { 5: boolean b1= true , b2= true ; 6: System.out.println(" boolean Result = "+ compare(b1,b2)+" \n "); 7: System.out.println(" Int Result = "+ compare(10,10)+" \n "); 8: System.out.println(" String Result = "+ compare(" ABC "," ABCE ")+" \n "); 9: System.out.println(" float Result = "+ compare(10.00f,10f)+" \n "); 10: System.out.println(" Mixed Result = "+ compare(10l,10l)+" \n "); 11: System.out.println(" Mixed[long,int...

How to avoid NPE while Auto-Unboxing

Auto-Boxing/Unboxing is introduced in Java 5 version. It supports automatic conversion of primitive type (int, boolean, float, double) to their equivalent Objects ( Integer, Boolean, Float, Double) in assignment , method and constructor invocation and other way also. Here is the examples Auto-Boxing Integer i = 10; // Auto-boxing converts primitive int value to Integer Object Auto-Unboxing int i = 0; i= new Integre(10); // Auto-Unboxing converts Integer Object to primitive int There is serious problem with using Auto-bocing/Unboxing, it may result null pointer exception. Take an example of following program package testproject; public class TestAutoUnboxing { private static TestAutoUnboxing test= new TestAutoUnboxing(); //cause Null Pointer Exception public static final Boolean YES = true; // Autoboxing for private boolean amIHappy = YES; // Instance Variable public static void main(String[] args){ System.o...