在Java中,字符串以用equals()方法或“==”来进行比较,用前者一般不会有问题。但使用“==”时,常常会发生问题,主要是因为“==”只对变量有效,对象引用的比较就不行了,因此字符串比较时还是用equals()方法比较保险。
下面的代码的输出结果可以很明白的看到两者的区别,
public class test1 {
public static void main(String[] args) {
String s1 = new String("test1"); // 创建的是字符串对象
System.out.println(s1.equals("test1")); // 返回true
System.out.println(s1 == "test1");// 返回false
String s2 = "test2";//创建的是字符串变量
System.out.println(s2.equals("test2")); // 返回true
System.out.println(s2 == "test2"); // 返回true
}
}
转载本文请联系原作者获取授权,同时请注明本文来自徐轶超科学网博客。
链接地址:http://blog.sciencenet.cn/blog-434746-379480.html