Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于《面试常备-字符串三剑客String-StringBuffer-StringBuilder》 的疑问 #12

Open
Treeveer opened this issue Sep 27, 2022 · 0 comments

Comments

@Treeveer
Copy link

Treeveer commented Sep 27, 2022

对于 str1 来说,new String("hello") 分两步走:首先,"hello" 属于字符串字面量,因此编译时期会在 String Pool 中查找有没有值为 "hello" 的引用,如果没找到,就在字符串常量池中开辟地址空间创建一个字符串对象,指向这个 "hello" 字符串字面量;
然后,使用 new的方式又会在堆中创建一个字符串对象。

对于 str3 来说,str1.intern() 会先在 String Pool 中查看是否已经存在一个字符串和 str1 的值相等,没有,于是,在 String Pool 中添加了一个新的值和 str1 相等的字符串,并返回这个新字符串的引用。

这两段话不是自相矛盾吗?str1.intern( )根本不会起作用,因为str1在 new( )的时候已经把"Hello"添加到常量池了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant