Cha*_*yak 4 java string jdk1.6
class Test{
public static void main(String s[]){
String s1="welcome",s2="come";
System.out.println(s1==("wel"+"come")); //prints : true
System.out.println(s1==("wel"+s2)); //prints : false
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么println方法都给出了不同的结果.请详细说明.
== 总是比较参考本身.
在第一次比较中,常量字符串表达式"wel" + "come"在编译时进行评估,因此您最终使用与用于初始化的文字相同的实习引用s1.
在第二种情况下,在执行时执行串联,创建新字符串.
要比较两个字符串的内容是否相等(而不是检查两个引用是否引用同一个对象),请使用equals:
System.out.println(s1.equals("wel" + "come"));
System.out.println(s1.equals("wel" + s2));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |