String position analysis

String is not a basic data type, so what is the memory location of a string? There are two situations:

1. String assignment directly:

String s = “String”;

The reference of s is stored in the stack memory, and the String pointed to by the reference is stored in the constant pool of the method area (first judge whether there is a haha ​​in the constant pool, and it will directly point to it if it exists)

2, string object new creation

String s = new String(“String”);

The reference of s exists in the stack memory, and the String object pointed to by the reference is stored in the heap memory (every new time, a new String object is created in the heap)

to sum up:

1. String type references are stored in the stack memory;

2. String reference points, direct assignment is stored in stack memory, and new is stored in heap memory.

Guess you like

Origin blog.csdn.net/weixin_39443483/article/details/114972786