No, because
String s1 = "mynameisbond";
uses a single string literal and
String s2 = "myname" + "isbond";
uses two that can be combined at compile time into a single literal.
But s5, s6, and s7 all get assigned at run time, not compile - so the strings they contain are not string literals: they are not "known" at compile time so they do not get added to the Constants Pool.
Quote:
If i do: String greet = new String("hello") , I know the string "hello" will be allocated to the HEAP but at the same time this "hello" will also be created in String Constant Pool? so in the next line if I do: String greet2 = "hello" , greet2 will point to the already existing "hello" by greet in the String Constant Pool or it never existed there because of new keyword of greet?
There are two ways to create a string:
String s="Welcome";
This creates a variable called
s
which "points" to a literal string "Welcome" in the Constant Pool.
String s=new String("Welcome");
This creates a variable called
s
, a string literal "Welcome" in the Constant Pool unless it already exists there, and a copy of the literal the heap - s "points" at the heap version.
The
new
keyword always constructs a heap based variable.