String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");结果为什么为false?

来源:学生作业帮助网 编辑:作业帮 时间:2024/12/02 04:42:48
String s1 =
xݒN@_ʊ +Q;}>#U+݈`ADBd*RRUȎBx Jlt=w4ύ֫KI/KT +ҭPB`2^A7oo׌bc$S+c H+8L H|{Y~c֨DuatK86MgmT8m'LLʹh"WtrY&6l H

String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");结果为什么为false?
String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");
String s1 = "a";
String s2 = "b";
String str6 = s1 + s2;
System.out.println(str6 == "ab");结果为什么为false?

String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");String s1 = "a"; String s2 = "b"; String str6 = s1 + s2; System.out.println(str6 == "ab");结果为什么为false?
String比较特殊,之前的s1和s2是在【栈】中,属于变量;str6属于对象,因为String不可以增加或者删减在创建后,所以s1+s2的结果是相当于创建了个String对象str6,此时str6存在于【堆】中,所以说,2者不同.
【==】比较的是 值
【equals】比较的是 地址

因为他们的值是相同的,但是他们的物理地址不同,不是一个对象,并不能认为是完全的相等(“==”)。
java中字符串比较推荐用equals,例如str6.equals("ab")