Java字符串文字串联
public static void main(String[] args){ one(); two(); three(); } public static void one() { String s1 = "hill5"; String s2 = "hill" + 5; System.out.println(s1==s2); } public static void two() { String s1 = "hill5"; int i =5; String s2 = "hill" + i; System.out.println(s1==s2); } public static void three() { String s1 = "hill5"; String s2 = "hill" + s1.length(); System.out.println(s1==s2); }
输出是
true false false
字符串文字使用实习过程,然后为什么two()
和three()
为false。我可以理解three()
但two()
不清楚。但需要对两种情况进行适当的解释。
有人可以解释正确的理由吗?
在2和3的情况下,编译器无法计算String的值,因为hill + i
是运行时语句,对于s1.length()
在这里阅读我问同样的情况 – 链接
想想这样, String s1 and s2
正在使用编译时常量, s1="hill5"
和s2="hill" + 5
,请记住,作为文字指定的字符串是常量,其状态不能被修改,因为String是不可变的 。
所以在编译时,编译器说“哦是的,它们被计算为相同的值,我必须为s1和s2分配相同的引用”。
但是在方法two()
和three()
,编译器说“我不知道,可能是i的值可以随时更改,或者s1.length()
随时更改”,它是运行时的东西,所以编译器没有把two()
和three()
方法的s2放在池中,
因此,它们是错误的,因为在运行时,一旦它被改变,就会创建新对象!!
具有编译时常量表达式的字符串将放在String池中。 主要条件是编译时常量表达式。 如果你在方法two()
中使局部变量final,那么two()
也将打印为true
public static void two() { String s1 = "hill5"; final int i =5; String s2 = "hill" + i; System.out.println(s1==s2); }
输出:
true