思考:
String s = new String(“hello”)和String s = “hello”;的区别?
字符串比较之看程序写结果
字符串拼接之看程序写结果
经过分析我们给出代码:
public class StringDemo3 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2)); //true
}
}
运行结果:
false
trueProcess finished with exit code 0
打开原码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i =