There are many ways to create a string in Java, such as:
string s = new String ("Riqi"); String s = "Riqi";
But what is the difference between the two?
You know, in Java, the new object is actually creating an object in the stack memory that refers to a reference type that points to the heap memory, and the string object cannot be changed once it is created.
Java provides a buffer pool mechanism for string types, that is, when a string object is created using double quotation marks, the Java environment first looks for the same content string from the string buffer pool, and if it is found, it is used directly, and if not, a new string is created and added to the string buffer pool. Like what:
String S1 = "Riqi"; String s2 = "Riqi";
It can be understood that the variables S1 and S2 both point to the same string storage object in the heap memory in the string buffer pool.
Because of the mechanism of the buffer pool, it is generally more efficient to use string s = "Riqi" When a new string object is required.
How to create string strings in different ways