“ == ” 比较是否为一个对象;
“ equals() ” 比较的是字符串的内容是否相同
String s2 = new String("Hello");
,这个对象实际上是存储在堆中的。new
关键字告诉 JVM 需要在堆上分配内存来存储这个新的 String
对象。
而变量 s2
,它是一个引用变量,存储在栈中。这个引用变量指向堆中实际存储的 String
对象。
public class Test{
public static void main(String args[]){
String s1 = "hello"; //以常量的形式赋值
String s2 = new String("hello"); //new创建字符串
String s3 = new String("hello");
boolean flag = s1==s2;
System.out.println("flag="+flag); //false
boolean flag2 = s2==s3;
System.out.println("flag2="+flag); //false
}
}
“ equals() ” 比较的是字符串的内容是否相同
public class EqualsTest{
public static void main(String args[]){
String s1 = "hello";
String s2 = new String("hello");
String s3 = new String("hello");
System.out.println(s1.equals(s2)); //true
System.out.println(s2.equals(s3)); //true
}
}