Comparison of two strings in Java (memory perspective)

1. First look at the memory distribution of the java virtual machine :


Program counter:

    ① The only area without an OutOfMemoryError condition.

    ②When the thread executes the java side, record the address of the virtual machine bytecode instruction being executed.

native method stack

virtual machine stack

   ①When a java method is executed, a stack frame is created, which can store information such as local variable table, operand, method exit and so on.

    ②It is mainly used to store local variables, variables of basic types, and references to objects (pointing to another memory area: the heap).

heap

    ①Thread shared area. Stores an instance of an object, an array.

The method area and the runtime constant pool in it

    ① Store the loaded class information, constants and static variables.

2. When creating an object, how is the memory allocated when the memory is allocated in the heap?

    ① The pointer collides. The pointer points to the dividing point between free and used.

    ② Free list. The list records the usage of memory blocks.

3. How are object instances in the heap associated with references to objects in the stack?

    ① handle access. The heap is divided into memory as a handle pool.

    ② direct pointer access. Directly store the address of the object in the heap.

4. Examples

String a="abc";//1
String b="ab"+"c";//2
String c=new String("abc");//3
String d=new String("ab")+"c";//4
String e=new String("abc");//5
sout(a==b);
sout(a==c);
sout(c==d);
sout(c==e);
sout(b==d);

Memory distribution map

Case 1: abc is a constant of type String, which is stored in the constant pool with the appearance of the method. String a is a reference to "abc", stored in the stack memory, pointing to "abc".

Case 2: When a string is formed by concatenating multiple string constants, it must also be a string constant itself, so b is also parsed as a string constant at compile time, stored in the constant pool, and referenced to b Stored in stack memory, pointing to abc in the constant pool.

Case 3: String c creates a reference to a string in stack memory, new String("abc") allocates a piece of memory in the heap, and c points to the memory allocated in the heap. Use new() to create a new object, it will be stored in the heap. A new object is created each time it is called.

Case 4: new String("ab") allocates a block in heap memory and "c" is in constant pool. String d is a reference to the object in the stack memory, pointing to these two pieces.

Case 5: String e creates a reference to a string in stack memory, new String("abc") allocates a piece of memory in the heap, and c points to the memory allocated in the heap. At this time, it is not the same heap memory area as Case 3.

From the above analysis, the result is obvious

true
false
false
false
false

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324551424&siteId=291194637