Example & Tutorial understanding programming in easy ways.

What is Java String Pool?

String is special class in Java and all String literal e.g. "abc" (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.

 example:

String s1 = "abc"; //1st String object

String s2 = "abc"; //same object referenced by name variable

String s3 = new String("abc") //different String object

//this will return true

if(s1= =s2){

System .out.println("both s1 and s2 is pointing to same string object");}

 //this will return false

if(s1= =s3){

System.out.println("both s1 and s3 is pointing to same string object");}

if you compare s1 and s2 using equality operator "==" it will return true because both are pointing to same object. While s1==s3 will be return false because they are pointing to different string object. It's worth remembering that equality "==" operator compares object memory location and not characters of String. By default Java puts all string literal into string pool, but you can also put any string into pool by calling intern() method of java.lang.String class, like string created using new() operator.
  

Read More →
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!