代码中:
String str1="hello";
String str2="imooc";
System.out.println("str1等于str2:" + (str1==str2));
是可以输出结果:str1等于str2:false
C中比较字符串一般会调用函数strcmp();,百度了JAVA中一般也会调用equals()方法,提及到字符串是对象类型和方法,不细究。看到后面再回头来自我解答。
而代码中==运行成功,是可以这样比较还是IDE将就着执行成功了,回头自我解答。
可以这样比较,但字符串比较用==表示的是地址的比较,指向同一对象才返回true,而equals是比较内容的
==和equals区别 (1)== 第一,指的是基本数据类型的数值大小的比较 例如:int a=3,b=3;则a==b; 第二,指的是比较对象引用(new出来对象或者是已经存在对象的首地址)是否相等 例如: String a = "hello"; String b = "world"; a指向的是内存存放字符串“hello”的首地址,b指向的是内存存放字符串“world”的首地址。因为这两个 字符串对象不同,故首地址不同。故a==b为false。 (2)equals 它的本意是指两对象引用是否相等,但是String类重写了它的equals方法(源码里有) 1.if(object==this) return true; 2.if(object instanceof String) 比较两个字符串字符是否相等,相同返回true,不相同返回false 例如 String a = "nice"; String b = "nice"; String c = new String("nice"); String d = new String("nice"); 表达式 a==b a和b指的是“nice”同一对象,故地址即引用相等。故为true 表达式 a==c c是重新new出来的对象 故a和c指的是不同的对象 故为false 表达式 a.equals(b) 将a,b带入equals方法。上面已经得出a==b为false 故不执行第一个if条件 转而进行第二个条件比较字符串的字符。都是“nice",故为true 表达式 a.equals(c) 同理也是比较字符串的字符都是‘nice’,故为true
代码
public class helloworld{
public static void main(String[] args){
String str1= new String("hello");
String str2= new String("hello");
System.out.println(str1==str2);
String str3="hello";
String str4="hello";
System.out.println(str3==str4);
}
}
结果:false
true
大概能意会==对于地址的比较了。
但如果直接定义str而不是用new,不同的字符串地址竟然是一样的。对于new的用法还是要回头来看。
String str1= new String("hello");
String str2= new String("hello");
用== 和 equals 分别试试就知道了
楼上正解
有这样的精神很好,有问题后面大家可以一起讨论