What is the difference between these two following statements?
String s = \"text\";
String s = new String(\"text\");
String str = new String("hello")
It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.
An object will be created in a heap memory area and str
reference points to object created in heap memory location.
if you want str
reference to point object containing in String constant pool then one has to explicitly call str.intern();
String str = "world";
It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.
In both the above case, str
reference points to String "world"
present in Constant pool.