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

Posted 码农搬砖_2020

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了美团面试题解析:用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。

以上是关于美团面试题解析:用final 考验你对堆和栈的理解的主要内容,如果未能解决你的问题,请参考以下文章

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

堆和栈的区别

iOS开发面试题:堆和栈的区别

面试题:堆和栈的区别

堆和栈的区别

高频面试题-请聊一下JVM中堆和栈的区别! 让这个12岁的年轻人为你讲解