From: http://wuyue37307.blog.163.com/blog/static/2758371200981103810985/
String A = new string ("B"); how many objects are there?
Haha. To understand this, we need to know how the string class works.
You know that in Java, except for the basic type in Java 8, all others are class objects and their references. Therefore, "XYZ" is a string object in Java. For a String object, its object value cannot be modified, that is, it is immutable.
See:
String S = "hello ";
S = "Java ";
String S1 = "hello ";
String S2 = new string ("hello ");
Ah, isn't the string object referenced by S Modified? Where did I go for immutability?
Don't worry. Let me tell you what happened:
During JVM operations, a piece of memory space will be created and saved to the string object. We call this memory space a string pool.
String S = "hello"; When JVM sees "hello", create a String object to store it in the string pool and return its reference to S.
S = "Java". When JVM sees "Java", create a new String object in the string pool to store it, and then return the reference of the New String object to S. The original "hello" is still in the string pool. It does not disappear and cannot be modified.
So we only changed the reference of S, but did not change the object referenced by S, because the value of the string object cannot be modified.
String S1 = "hello"; JVM first finds the "hello" character string in the string pool, finds it, and returns its reference to S1. Otherwise, a New String object is created, put it in the string pool. Here, because S = "hello", the object has been referenced, so according to rules S and S1, the same object is referenced. So S = S1 will return true. (==, For non-basic types, it is to compare whether two references reference the same object in memory)
String S2 = string ("hello"); JVM first finds the string "hello" in the string pool and does not do anything. Otherwise, a New String object is created, put it in the string pool. Because New is encountered, the string object storage "hello" will be created in the memory (not in the string pool), and the memory (not in the string pool) will be) string object is returned to S2. So S = S2 will return false, not to reference the same object.
Now let's look at the question:
String S = new string ("XYZ ");
First, find it in the string pool? Do not create a String object; otherwise, create a String object.
When the new operator number is encountered, create a String object in the memory and return it to S. Another object
So there are two objects in total.