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