假设有以下代码String s = "hello":String t = “hello”;char c [ ] = {'h','e','l','l','o'};
下列选项中返回false的语句是?
A. s.equals (t);
B. t.equals (c);
C. s==t;
D. t.equals (new String (“hello”));
答案:B
首先==与equals是有明显区别的。
==强调栈中的比较,可以理解为地址比较,equals强调对象的内容比较。
String s=“hello”;
会在栈中生成hello字符串,并存入字符串常量池中。
String t=“hello” ;
创建时,会在字符串常量池中寻找,当找到需要的hello时,不进行字符串的创建,引用已有的。
所以,s==t返回true,s.equals(t)也是true。
`char c[]={‘h’,’e’,’l’,’l’,’o’}; c==s这个是不存在的,==两边类型不同
t.equals(c)这个语句在anObject instanceof String这步判断不会通过,也就是cha[] 压根不能与String相比较,类型不是相同的。返回false