I have two questions:
public static void main(String[] args) {
String s1 = "bla";
String s2 = "b" +"l" + "a";
String s3 = "b".concat("l").concat("a");
if(s1 == s2)
System.out.println("Equal");
else
System.out.println("Not equal");
if(s1 == s3)
System.out.println("Equal");
else
System.out.println("Not equal");
}
-
Why does
s1ands2point to the same object, whereass1ands3doesn’t? (There is no usage ofnewkeyword). -
If I get a string from the user and add to the above code these lines:
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String name=in.readLine(); if(name.equals("test")) s1 = s1 + "xyz";If the user enters
xyzthe program will printNot equal, when the user enters another thing the program outputsEqual. Does this mean that the pool changes through the execution of the whole program? Does the optimizer works at the compile time and continues to work in theruntime?
Because the concatenation happens at compile time, and the completed string therefore goes in the constant pool the same as in the first example. It’s a special case “known” to the compiler. It’s really meant so that long strings, concatenated this way over several lines, still get the benefit of the same performance improvements as simple string constants.
In the second example, you’re performing the calculation at runtime, so it won’t be part of the constant pool.
Note however that in the JLS the details of what can and can’t go in the string constant pool is deliberately left vague, so different implementations may optimise in different ways. It specifies certain rules as to what has to go in there, but don’t rely on this behaviour being consistent across implementations.