class Test
{
public static void main(String[] args)
{
/*String s1="Hello";
String s2="Hello";
String s3=new String("Hello");
System.out.println(s1==s2);//true?
System.out.println(s1==s3);//false?
*/
String s1="H";
String s2="ello";
String s3=s1+s2;
System.out.println(s3);
System.out.println(s3=="Hello");//false?
System.out.println(s3.equals("Hello"));//true?
}
}
问号处是为什么?
谢谢
{
public static void main(String[] args)
{
/*String s1="Hello";
String s2="Hello";
String s3=new String("Hello");
System.out.println(s1==s2);//true?
System.out.println(s1==s3);//false?
*/
String s1="H";
String s2="ello";
String s3=s1+s2;
System.out.println(s3);
System.out.println(s3=="Hello");//false?
System.out.println(s3.equals("Hello"));//true?
}
}
问号处是为什么?
谢谢
System.out.println(s3=="Hello");//false?
System.out.println(s3.equals("Hello"));//true?
说明s3和"Hello"指的地方不是同一对象。s3.equals("Hello")至于这个是true,equals这个方法是可以重写,你可以去看看源码,是一个个字符进行比较的。
== 比较的是引用的地址是否相同
而 String 类中的 equals 方法是重写了 Object 类的 equals 方法,比较的是对象的值,所以得到的值是 TRUE。