Thursday, March 14, 2013

What is String Pooling in Java?

When we create string literals jvm maintains all of them in pool known as String pooling.
 for exapmle,

    String str1 = "Hello"; //case 1
    String str2 = "Hello"; //case 2
   
    In case 1, iteral str1 is created newly and kept in the pool. But in case 2, literal str2 refer the str1, it will not create new one instead.
    
       if(str1 == str2) System.out.println("equal"); //Prints equal.
      
       // case 3
      String newString1 = new String("Hello");
      String newString2 = new String("Hello");
      if(newString1 == newString2) System.out.println("equlal"); //No output.
     
      Pooling is done for only string literals. In case 3 it gives no output because both string has a different reference.

Wednesday, March 6, 2013

What is Auto Boxing in Java?

Autoboxing is a new feature offered in the Java SDK 1.5 . In short auto boxing is a capability to convert or cast between object wrapper and it's primitive type.Previously when placing a primitive data into one of the Java Collection Framework we have to wrap it to an object because the collection cannot work with primitive data. Also when calling a method that requires an instance of object than an int or long, than we have to convert it too.

But now, starting from version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explisit object casting.

Here an example how it will look like using the Autoboxing feature:

Conversion of int into Integer and Integer into int

int inative = 0;

inative = new Integer(5); // auto-unboxing

Integer intObject = 5; // autoboxing