程序,我发现了与你分享的有趣的事情. foo()给出输出(s == s1)= false,bar给出(s == s1)= true.
我想知道为什么会这样.
public class StringTest { public static void main(String[] args){ foo(); bar(); } public static void foo(){ String s = "str4"; String s1 = "str" + s.length(); System.out.println("(s==s1) = " + (s1==s)); } public static void bar(){ String s = "str4"; String s1 = "str" + "4"; System.out.println("(s==s1) = " + (s1==s)); } }
在前一种情况下,在编译期间无法优化length()调用.在运行时,会创建一个新的字符串对象,该字符串对象与字符串常量不同(但等于它)
翻译自:https://stackoverflow.com/questions/6358280/why-do-i-get-different-results-when-comparing-strings-after-using-different-conc