What is the difference between these two following statements?
String s = \"text\";
String s = new String(\"text\");
String literals will go into String Constant Pool.
The below snapshot might help you to understand it visually to remember it for longer time.
Object creation line by line:
String str1 = new String("java5");
Using string literal "java5" in the constructor, a new string value is stored in string constant pool. Using new operator, a new string object is created in the heap with "java5" as value.
String str2 = "java5"
Reference "str2" is pointed to already stored value in string constant pool
String str3 = new String(str2);
A new string object is created in the heap with the same value as reference by "str2"
String str4 = "java5";
Reference "str4" is pointed to already stored value in string constant pool
Total objects : Heap - 2, Pool - 1
Further reading on Oracle community