Wednesday, March 19, 2014

When should we use intern method of String on String constants

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

String s = "Example";

String s1 = new String("Example"); // will create new object

String s2 = new String("Example").intern(); // this will create new object
 // but as we are calling intern we will get reference of pooled string "Example

No comments:

Post a Comment