昨天这个问题由Interviewer询问该线路的输出是什么.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我看着这个问题,然后思考面试官提出的简单问题.我告诉他,输出s1==s2和s3==s4返回true和true我是非常有信心.突然间,他说不是错误的输出然后我认为他可能是在开玩笑或试图失去信心,但直到最后他说错了.当我检查输出是true和false.我也在想如何通过给出适当的答案来解决我的困惑.提前致谢.
s1+s2在编译时不知道,因此它在运行时计算并创建一个新对象,每次运行时都不同.如果将s1和s2更改为final,编译器将内联常量,您将得到真的s3==s4.
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.
Run Code Online (Sandbox Code Playgroud)
要么
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.
Run Code Online (Sandbox Code Playgroud)
但
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.
Run Code Online (Sandbox Code Playgroud)