new String ( "123") created several objects?

String object could not be more familiar, face questions related to this often leads to memory performance optimization problem, this chapter show with new String ( "123") created several objects, for example record.

First, you can answer it correctly

String a = "123";

As defined above, is constant;

String b = a +"456";

As for the variable b, why? Is Constant Constant splicing get is a missing link?

No, constant stitching still get constant is constant.

But this time will be as a reference, is no longer a constant, and a variable, so the resulting b nature is variable.

String b = "123" + "456"

In this case b is a constant.

If you add a modifier to the final, it is a constant, so it is a constant a b.


Second, the definition of the difference between String constants and variables

We come back in two written analysis:

String a = "123";
String b = new String("123");

As the first row, we define a constant a, the second row, in the form of new keyword to create a variable b.

We learned before we go any further JVm combine some of the first line opened up a constant pool space, storage string 123, through a constant target point to the object. Line 2 since a new keyword, it will open up a space in the heap memory area, which is stored in string 123, and the memory address of the variable b imparted.

Therefore, a == b it? Shown to be false, is a heap memory is a constant pool.

If a modified:

String a = new String("123");

So, a == b it?

It is still false.

why? As long as through new forms naturally create two objects, it is false, even if their value is the same.

Third, the summary String constants variables

String constants stored in the constant pool, jvm considered in the optimization, make content objects share the same memory block, but the variable is on, different new definitions of different variables heap memory address space.

String constant connection constants, or constants, still with a constant pool management, but constant connection variable is a variable.

Fourth, create several objects of practice

Following cases (not considered in the case of a string constant pool already exist):

1、String a="123";

It creates an Object

jvm在编译阶段会判断常量池中是否有 "123" 这个常量对象如果有,a直接指向这个常量的引用,如果没有会在常量池里创建这个常量对象。

2、String a=new String("123");

创建了2个对象

同情况1,jvm编译阶段判断常量池中 "123"存在与否,进而来判断是否创建常量对象,然后运行阶段通过new关键字在java heap创建String对象。

3、String a="123"+"456";

创建了1个对象

jvm编译阶段过编译器优化后会把字符串常量直接合并成"123456",所有创建对象时最多会在常量池中创建1个对象。

4、String a="123"+new String("456");

创建了4个对象

常量池对象"123" ,"456",new String("456")创建堆对象,还有一个堆对象"123456"。

最后练习参考文章:https://blog.csdn.net/baidu_27969827/article/details/79219708

Guess you like

Origin www.cnblogs.com/niceyoo/p/11100090.html