String is not a primitive data type

The String class is a Java class that manipulates strings. Byte 2.short 3.int 4.long 5. Boolean 6. Float 7. Double 8

See the JDK source code for the String class definition

JDK 1.8 defines character arrays

private final char value[]; 

JDK 1.9 defines byte arrays

private final byte[] value; 

Source code analysis: From the source code can be seen, the string on the array of a packaging application, Java program at the bottom of the inside to provide a special string object pool. (that is, an array of strings, which is essentially heap memory)

The String class is instantiated in two ways.

1. Direct Assignment
In the process of direct assignment, the object can be automatically saved to the string object pool. In this way, if there is the same data definition, the object will be first searched to see if there is the same object in the string object pool, and if there is, the object will be directly pointed to it. In this way, the object reuse can be realized and the generation of objects can be reduced.

Such as:

String a = "aishu"; // Assign String b = "aishu"; // the "aishu" referred to by "b" and "aishu" referred to by "a" are the same number of words in the string. a == b; // true
2. Constructor instantiation
  • One of the two instantiated objects is anonymous (in the heap memory, and there is no reference to it in the stack memory, so the garbage object is generated). The other is a new object that is used by the program.
  • Will not be automatically saved to the object pool, unable to achieve reuse of objects
  • You can manually save it to the object pool by calling the intern() method

Use the following examples for specific analysis:

String a = new String("aishu"); // instantiate the constructor

Memory analysis: “Aishu” is an anonymous object in the heap in the application, and a new heap is created to hold “Aishu” for the application to use. The anonymous object is just sitting in the heap with no reference to it, so it becomes a garbage object in memory. Use up program memory.