String string1= “helloWorld”;
String string2 = new String(“helloWorld”);
问: string1 == string2 是true还是false?
为什么?
String string3 = “hello”;
String string4 = “World”;
问:string1 == (string3+string4)是否正确?
为什么?
问:string1 == (“hello”+”World”)是否是正确的?
为什么?
以前在面试时曾碰到过这样的问题,这里做一下记录。以便以后回顾。
public static void main(String[] args) {
String string1= "helloWorld";
String string2 = new String("helloWorld");
//判断strin1 与string2是否相等
System.out.println("String判断两个值是否相等,不能使用==,因为它对比的是地址:"+(string1 == string2));
System.out.println("String判断两个值是否相等,要使用equals来对比 :"+(string1.equals(string2) ));
System.out.println("====================================================");
String string3 = "hello";
String string4 = "World";
//判断string3+strin4是否与string1相等,使用==结果是false,因为它会新生成一个新的字符串地址
System.out.println(""+string1 == (string3+string4));
System.out.println(string1.equals(string3+string4));
System.out.println("====================================================");
//如果使用("hello"+"World") 与string1相比,得到的值是相同
/**
* 原因:"hello"+"World"是字面量(string3+string4都是对象,它们在加时,使用的是地址),并不是对象,所以他们在进行对比时
* 会先把"hello"+"World" = "helloWord",然后在内存共享区(也就是常量池)中去找有没有,发现已经有了,所以就直接这个地址返回,
* 这个地址正好与string1引用的是同一个,所以他们得出的值为true
*/
System.out.println("如果使用字面量\"hello\"+\"World\"去与string1比较,得到的结果是:"+(string1 == ("hello"+"World")));
}
》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
结果如下:
String判断两个值是否相等,不能使用==,因为它对比的是地址:false
String判断两个值是否相等,要使用equals来对比 :true
====================================================
false
true
====================================================
如果使用字面量"hello"+"World"去与string1比较,得到的结果是:true
这里主要有两个地方不好理解:
1:
String string3 = “hello”;
String string4 = “World”;
String string1 = “helloWorld”;
拿(string3+string4)使用 == 与string1对比时,为什么 得到的值 是false?
原因在于:string3+string4在此时都是对象,并不是字面量,所以他们在对比时,会先开辟一块空间并返回空间地址,再把string3与string4的值组合起来放进去,那么此时,拿一个新的空间地址与string1的空间地址进行比较,明显不是同一个,所以得出的值就是false
2:
如上述所说,string3+string4相加使用了新的空间保存,但为什么“hello”+”World” 去与string1的空间地址又是同一个呢?
原因很简单:这时的”hello”+”World”都是常量(字面量),所以虚拟机在处理时先把”hello”+”World”进行了处理组合,得到的一个新的常量(字面量):helloWorld,这时拿helloWorld去常量池中去有没有相同,因为string1指向的空间值正好是helloWorld,所以就不在创建空间,直接 把string1指向的空间返回了,这时,拿string1的空间与它自己进行对比,当然是相同的了。
其实它主要考的是虚拟机处理常量的规则,只要了解这一点,这些问题也就知道答案了。