Java:String之间通过==比较的情况

大家都知道在String之间的内容比较的时候,是通过equals函数比较的。

但是在在许多的面试题中,总是出现一堆的判断两个String对象通过==比较的结果,实际上是考的Java内存分配机制。

Java内存分配机制中,常量是保存到常量区的,而对象是保存到堆里面的,基本类型的临时变量是保存到栈里面的,所以就有了下面的一段代码:

public class Test {

    public static void main(String[] args) {
        String x = "abc1";
        String s = "1";
        int i = 1;

        String y = "a" + "b" + "c" + 1;
        System.out.println(x == y);//true

        y = "a" + "b" + "c" + "1";
        System.out.println(x == y);//true

        y = "ab" + "c" + 1;
        System.out.println(x == y);//true

        y = "ab" + "c" + 3 % 2;
        System.out.println(x == y);//true

        y = "abc" + s;
        System.out.println(x == y);//false

        y = "abc" + i;
        System.out.println(x == y);//false

        y = "abc" + getS();
        System.out.println(x == y);//false

    }

    public static String getS() {
        return "1";
    }
}

从这段代码可以看出,如果想要x==y是true,则x和y都必须是通过常量初始化的或拼接得到的,否则都会返回false。

转载于:https://www.cnblogs.com/ScorchingSun/p/6591908.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值