String的Equals和==,Integer的Equals和==,java基础必考面试题详解

public class EqualsTest {
	public static void main(String[] args) {
		String s1 = "s";
		String s2 = "s";
		System.out.println("s1 == s2:" + (s1 == s2));
		System.out.println("s1.equals(s2):" + s1.equals(s2));
		String t1 = new String("s");
		String t2 = new String("s");
		System.out.println("t1 == t2:" + (t1 == t2));
		System.out.println("t1.equals(t2):" + t1.equals(t2));
		Integer a1 = 129;
		Integer b1 = 129;
		System.out.println("a1 == b1:" + (a1 == b1));
		System.out.println("a1.equals(b1):" + a1.equals(b1));
	}
}

这是老生常谈的面试题

执行结果:

s1 == s2:true
s1.equals(s2):true
t1 == t2:false
t1.equals(t2):true
a1 == b1:false
a1.equals(b1):true

比较难以理解的是一下两个代码

public class EqualsTest {
	public static void main(String[] args) {
		String s1 = "s";
		String s2 = "s";
		System.out.println("s1 == s2:" + (s1 == s2));
	}
}

执行结果为true,为什么为true呢,我们来分析一下

1、两个string对象都是作为一个基本类型来使用的,而不是通过new关键字来创建的,因此虚拟机不会为两个string对象分配新的内存堆,而是到string缓冲池中寻找。

2、s1寻找string缓冲池内是否有s相同值的string对象存在,此时string缓冲池内是空的,没有相同的值string对象存在,所以虚拟机会砸string缓冲池内创建此string对象,其动作就是new string("s"),然后把string对象引用赋值给s1

3、s2寻找string缓冲池内是否有s相同值的string对象存在,此时虚拟机找到了一个其相同值得的string对象,这个string对象其实就是为s1所创建的对象,既然找到了一个相同的对象,那么虚拟机就不在为此对象创建一个新的对象,而是直接把存在的string对下岗引用赋值给s2

4、既然s1和s2所引用的是同一个对象,即自己等于自己,所以以上两种方法都返回true

public class EqualsTest {
	public static void main(String[] args) {
		Integer a1 = 129;
		Integer b1 = 129;
		System.out.println("a1 == b1:" + (a1 == b1));
	}
}

执行结果为false

public class EqualsTest {
	public static void main(String[] args) {
		Integer a1 = 127;
		Integer b1 = 127;
		System.out.println("a1 == b1:" + (a1 == b1));
	}
}

执行结果为true

为什么Integer为129时为false,为127时为true

原因是说-128和127之间的值会缓存到IntegerCache.cache中,所以Integer 在-128到127之间时,返回的是同一个对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值