-
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”;
// true.
String s2 = “hello”;
System.out.println(s1==s2);
Object s2 is the same object with s1. But if you create using new operator:
String s1 = “hello”;
//false
String s2 = new String(“hello”);
System.out.println(s1==s2);
Here is a great article about Strings.
Advertisements