Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

java - When does the pool change?

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 s1 and s2 point to the same object, whereas s1 and s3 doesn't? (There is no usage of new keyword).

  • 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 xyz the program will print Not equal, when the user enters another thing the program outputs Equal. 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 the runtime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why does s1 and s2 point to the same object, whereas s1 and s3 doesn't? (There is no usage of new keyword).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...