美团面试题解析:用final 考验你对堆和栈的理解

 * 微信公众号:码农搬砖
 * 欢迎关注我们,获得更多的面试知识
 */
public class TextFinal {/**
     * 考题1 :请问 输出结果
     */
    public static void test1() {
        String s = "hello2";
        final String s1 = "hello";
        String s2 = s1 + 2;
        System.out.println(s == s2);
    }/**
     * 考题2 :请问 输出结果
     */
    public static void test2() {
        String s = "hello2";
        String s1 = "hello" + 2;
        System.out.println(s == s1);
    }/**
     * 考题3 :请问 输出结果
     */
    public static void test3() {
        String s = "hello2";
        String s1 = s + 2;
        System.out.println(s == s1);
    }public static void main(String[] args) {
        test1(); // 结果 true
        test2(); // 结果 true
        test3(); // 结果 false
    }
​
​
}

考点:

(1)字符串常量池中的值都是唯一的

(2)编译期/运行时

(3)堆/栈

解析:

test2()函数解析

String s = “hello2”; hello2 会存在常量池中

String s1 = “hello” + 2;
两个常量相加,在编译期执行,生成的hello2,但是此时常量池中已经有了hello2,上面说到字符串常量池中的值都是唯一的,所以 S 和
S1指向同一个位置。因此 返回true。

test3()函数解析

String s = “hello2”; hello2 会存在常量池中

String s1 = s + 2; s是一个引用 ,在运行期执行,会生成一个新的对象,存在堆中,因此 s1
指向一个新的地址,s指向了常量池中。地址不等,因此返回fasle。

test1()函数解析:

String s = “hello2”; hello2 会存在常量池中 final String s1 = “hello”;
String s2 = s1 + 2; 由于final 修饰,S1+2
发生在编译期,等于两个常量相加,上面说到字符串常量池中的值都是唯一的,所以 S 和 S2指向同一个位置。因此 返回true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值