当前位置:网站首页>String ABC = new string ("ABC"), how many objects are created

String ABC = new string ("ABC"), how many objects are created

2022-07-06 13:39:00 Wake up duck, did you program today?

String abc = new String("abc");

Let's not worry about answering this question. How many people have been created , First analysis :

First of all, there is a ‘new’ keyword , We've probably heard of everything new What comes out is put in the pile , This keyword is when the program is running , According to the loaded system classes String Instantiate a string object in the heap , And then here String The construction method of passes a “abc” String , because String The bottom layer of the string member variable inside is final Embellished , So it's a string constant , therefore JVM Can take a literal measure “abc” Go to the string constant pool to find , One corresponding to it String Object reference of , If you can't get it, you will create one in the heap memory “abc” Of String object , And save the reference to the string constant pool , And save the reference to the string constant pool , If there is any more literal quantity in the future “abc” The definition of , Because the string constant pool , Literal quantity already exists “abc” A reference to , So you only need to get the corresponding reference from the constant pool, and you don't need to create .

For this problem, I think there are two

  1. If ”abc“ This string constant does not exist , You need to create two objects , Namely ‘abc’ This string constant , as well as ‘new String’ This instance object
  2. If ‘abc’ This string constant exists , Then only one object will be created , Namely String This object .

The above is the full explanation of this problem , Mainly investigated right JVM There are runtime memory partitions and JVM The understanding of constant pool is deep enough to answer .

原网站

版权声明
本文为[Wake up duck, did you program today?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916452333.html