This is a question that I got in an interview.
I\'ve two strings defined as
String s1=\"Java\";
String s2=\"Java\";
My question i
When compiler optimizes your string literals, it sees that both s1 and s2 have same value and thus you need only one string object. It's safe because String is immutable in Java.
String s1="Java";
String s2="Java";
System.out.println(s1== s2);
This gives result true
because s1
and s2
points to the same object.
String Pool is the mechanism that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.