游泳池什么时候改变? [英] When does the pool change?

查看:83
本文介绍了游泳池什么时候改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题:

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");
}




  • 为什么 s1 s2 指向同一个对象,而 s1 s3 不是吗? (没有使用关键字)。

    • 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";
      

      如果用户输入 xyz ,该程序将print 不等于,当用户输入另一个东西时,程序输出 Equal 。这是否意味着池通过执行整个程序而改变?优化器是否在编译时工作,继续在运行时 中工作?

      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?

      推荐答案


      为什么s1和s2指向同一个对象,而s1和s3不指向? (没有使用新关键字)。

      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.

      但请注意,在JLS中有什么可以和不可以的细节进入字符串常量池故意留下模糊,因此不同的实现可能以不同的方式进行优化。它指定了某些具有的规则,但不依赖于这种行为在各种实现中保持一致。

      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.

      这篇关于游泳池什么时候改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆