执行 new String("hello") 可能创建 一个或两个对象,具体情况取决于 "hello" 是否已经存在于字符串常量池中。
情况分析
-
如果常量池中已存在
"hello"字符串:new String("hello")会直接在堆中创建一个新的String对象,并且这个对象的值指向常量池中的"hello"。- 这种情况下,
new String("hello")只会创建 1 个对象(即堆中的String对象)。
-
如果常量池中不存在
"hello"字符串:- 首先会在字符串常量池中创建
"hello"字符串常量。 - 然后
new String("hello")在堆中创建一个新的String对象。 - 这种情况下,
new String("hello")会创建 2 个对象(常量池中的"hello"和堆中的String对象)
- 首先会在字符串常量池中创建
浙公网安备 33010602011771号