Posts Tagged string pool

Ways of Creating Strings in java: String Literal Pool

    String Literal Pool:

String str=”hello”;
willl go to String literal pool managed by String class and will reuse the “hello” string if it is already present, otherwise creates new “hello” in pool.
String str=new String(“hello”)
every time creates new object in heap.

Garbage collector never looks in String literal pool. String literal pool is also a part of heap memory.

So:

String s1 = “hello”;
String s2 = “hello”;
System.out.println(s1==s2);
// true.

Object s2 is the same object with s1. But if you create using new operator:

String s1 = “hello”;
String s2 = new String(“hello”);
System.out.println(s1==s2);
//false
Here is a great article about Strings.

Advertisements

Leave a comment