Storage of variables in Java notes

1. Java variable storage domain

The storage areas of Java variables are mainly placed in the following places:

(1) Register: it can be said to be the fastest storage area. Register variables can be declared in C / C + +, but register variables cannot be declared in Java, which is only determined by the compiler at compile time.

(2) Stack: store references to basic type data and objects, but the object itself is not in the stack. The object (through new) is placed in the heap or in the constant pool (the constant object of string is placed in the constant pool).

(3) Heap: used to store new objects.

(4) Constant pool: a constant that holds string constants and basic type data (modified by public static final).

(5) Static domain: used to store static members.

(6) Non RAM storage: such as hard disk, etc.

Here we mainly talk about heap, stack and constant pool. The size and life cycle of the data stored in the stack are determined. When the referenced data disappears, the stack data will be recycled by the JVM. The data stored in the heap is uncertain. When certain conditions are met, it will be recycled by the JVM's garbage collection mechanism.

2. Examples

For example, the following code:

For S1 and S2, they will be stored in the constant pool. For S3 (new object), they will first look for the object with "example" in the constant pool. If so, a copy object with "example" will be created in the heap. If not, they will first create an object with "example" in the constant pool, and then create a copy object in the heap.

So there is a question: how many objects does string STR = new string ("ABC") create?

Answer: one or two.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>