如果两个字符串具有相同的引用,为什么输出不被排除(true)?

时间:2015-08-25 17:00:53

标签: java string

昨天该问题由访问员询问该行的输出是什么。

public class StringTest {

  public static void main(String[] args) {
      String s1 = "abc";
      String s2 = "abc";
      String s3 = s1+s2;
      String s4 = s1+s2;

      //check s1 == s2
      System.out.println(s1==s2);

      //check s3 == s4
      System.out.println(s3==s4);
  }
}

当我看着这个问题,然后思考面试官提出的简单问题。我告诉他输出s1==s2s3==s4将返回truetrue,我非常自信。 突然间,他说不是错误的输出然后我认为他可能是在开玩笑或试图失去信心,但直到最后他说错了。 我检查时输出为truefalse。 我也在想如何通过给出适当的答案来解决我的困惑。 提前谢谢。

2 个答案:

答案 0 :(得分:6)

s1+s2在编译时是未知的,因此它在运行时计算并创建一个新对象,每次运行时都不同。如果将s1和s2更改为final,编译器将内联常量,s3==s4将为true。

  final String s1 = "abc";
  final String s2 = "abc";
  String s3 = s1+s2; // compiler replaces with "abcabc"
  String s4 = s1+s2; // compiler replaces with "abcabc"

  //check s1 == s2
  System.out.println(s1==s2);

  //check s3 == s4
  System.out.println(s3==s4); // is now true.

OR

  String s1 = "abc";
  String s2 = "abc";
  String s3 = (s1+s2).intern(); // use the string literal pool
  String s4 = (s1+s2).intern();

  //check s1 == s2
  System.out.println(s1==s2);

  //check s3 == s4
  System.out.println(s3==s4); // is now true.

BUT

  String s1 = "abc";
  String s2 = "abc";
  // String s3 = s1+s2;
  String s3 = new StringBuilder().append(s1).append(s2).toString();
  // String s4 = s1+s2;
  String s4 = new StringBuilder().append(s1).append(s2).toString();

  //check s3 == s4
  System.out.println(s3==s4); // different objects.

答案 1 :(得分:-1)

因为字符串是不可变的并且在编程中无处不在,所以JVM使用a 具有相同字符序列的字符串文字的唯一实例,以提高效率并节省内存。这样的实例称为实习字符串 让我们说:

String s1 = "xyz";
String s2 = "xyz";

在前面的陈述中,s1s2引用相同的实习字符串 - " xyz" -so s1 == s2为真。 s3s4不是这种情况。您可以在Google上阅读有关Interned Strings的更多信息。