Java String is Special
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.
For performance reason, Java’s String is designed to be in between a primitive and a class.
例如
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
**注意:***字符串文字*存储在公共池中。这有助于共享具有相同内容的字符串的存储,以节省存储。通过new运算符分配的字符串对象存储在堆中,并且没有共享相同内容的存储。