How many objects did the string create?

Source: Internet
Author: User

Java code

    1. String str=New string ("AAA");

How many string objects does this line of code create? The answer is 2 instead of 3. Since the new String ("AAA") is equivalent to "AAA" and one is the original instance object that was created when placed in the heap, and the other is the "AAA" object placed in the constant pool, of course, the STR itself is simply a reference, placed in the stack, to point to the object created in the heap.

Chang (constant pool) refers to some data that is determined at compile time and is saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, and also includes string constants.

Java code

    1. String str="AAA";

Only 1 objects are created. This involves a string constant pool, which has a string pool in the JVM that is used to hold many string objects that can be shared, so that if we use the same literal string, it uses the literal string in the string pool. Of course we can use the Intern () method of the string object to access the constant object that the string object corresponds to in the string pool.

When this line of code is executed, the JVM looks in the string pool to see if an object with the value "AAA" already exists, and if it does, no longer creates a new object, returns a reference to the existing object directly, and if it does not, it is created first, then added to the string pool, and its reference is returned.

Java code

    1. String str1="AAA";

    2. String str2="AAA";

Only 1 objects are created. The above explanation is even clearer, when executing the second line of code, the AAA string object already exists in the pool, so it returns directly to the string object that already exists in the pool.

Java code

    1. String str="AAA"+"BBB";

Or only 1 objects are created. Since the constant string is also determined at compile time, and because both "AAA" and "BBB" are constants, the value of the variable str can be determined at compile time. This line of code compiles with string str= "aaabbb"; Is it the same as we usually do? Generally using "+" to concatenate two strings will result in another new character object. Let's take a look at the example below to understand:

Java code

  1. String str1 = "AAA";

  2. String str2 = "BBB";

  3. String STR3 = "aaabbb";

  4. String STR4 = "AAA" + "BBB"; //does not produce a new string object

  5. System.out.println (STR3 = = STR4); //true

  6. STR4 = str1 + "BBB"; //will produce a new string object

  7. System.out.println (STR3 = = STR4); //false

  8. STR4 = str1 + str2; //will produce a new string object

  9. System.out.println (STR3 = = STR4); //false

From the above example, we can conclude that the two strings connected using "+" are themselves literal constant strings, and if there is such a concatenated string in the pool, the object will not be recreated, but the string object in the pool is directly referenced; A new string object is generated as long as one of the two strings in the connection is not a literal constant string (that is, defined).
There are exceptions to everything, and this is no exception: if two or one of the strings in the "+" connection is not a literal constant, the situation changes if you define a constant string:

Java code

  1. Final String str1 = "AAA";

  2. Final String str2 = "BBB";

  3. String STR3 = "aaabbb";

  4. /*

  5. * Because both STR1 and STR2 are defined as constants, they can be determined at compile time, and the constants are replaced at compile time, equivalent to

  6. * STR4 = "AAA" + "BBB", so no new objects are generated

  7.  */

  8. String STR4 = str1 + str2;

  9. System.out.println (STR3 = = STR4); //true

However, if the final string is defined first but not initialized at the definition, it is initialized in the block as follows:

Java code

  1. //At this time str1 and str2 are equivalent to variables, not often, because blocks are determined at run time and cannot be determined at compile time

  2. Final Static String str1;

  3. Final Static String str2;

  4. Static {

  5. STR1 ="AAA";

  6. STR2 ="BBB";

  7. }

  8. Public Static void Main (string[] args) {

  9. String STR3 = str1 + str2;

  10. String STR4 ="aaabbb";

  11. System.out.println (STR3==STR4); //output is false

  12. }

  13. String str=""; with string str=new string ();

  14. str="" will be placed in the pool, but new String () will not be placed in the pool.


The Intern () method of the string
"When the Intern method is called, if the pool already contains a string equal to this string object (the object is determined by the Equals (object) method), the string in the pool is returned, otherwise this string object is added to the pool and a reference to this string object is returned. It follows that for any two strings s and T, when and only if S.equals (t) is true, s.intern () = = T.intern () is true ", which is the original source annotation for the JDK document.

Now let's go back to the very beginning of the example, why string Str=new string ("AAA"); Produce 2 objects? One is "AAA" and as a string constructor argument, but "AAA" itself is a string, before passing into the constructor has created a character object, in essence, is like a second instance: string str= "AAA"; , the string object it creates is put into the pool, and the reference is also the string object in the pool, and the other is created by using the new string () constructor. So the new string ("AAA") produces two objects, that is, when a string object is created in this way, the string parameter object is placed in the object pool and a separate string object is created.

Understand why the new string ("AAA") produces two objects, and we'll look at new string (char value[]) in such a way as to create a string object into the pool? The answer is no. Because a character array is passed to the constructor, instead of putting the string parameter itself into the pool, as in the case of a literal constant string parameter passed earlier. So now if we prove that the new string (char value[]) did not put the string object into the pool, we could write a simple test that opened the XP Task manager at runtime and looked at the operating system's memory usage to be able to confirm initially:

Java code

  1. int size = 10000000;

  2. char c[] = new char[size];

  3. for (int i = 0; i < size; i++) {

  4. C[i] = ' a ';

  5. }

  6. //When creating a string with a character array parameter constructor, the string object is not placed in the string pool

  7. String str1 = new string (c);

  8. System.out.println ("string string object creation completed ...");

  9. Thread.Sleep (the);

  10. Str1.intern (); //To see memory increase

  11. System.out.println ("First call intern () complete ...");

  12. Thread.Sleep (the);

  13. Str1.intern (); //In another 5 seconds will not see memory growth, because the pool has, and will not be put, so memory no change

  14. System.out.println ("second call intern () complete ...");

  15. Thread.Sleep (the);

So there are two ways to create a string object and put it into the pool: the first is to use literal constants to define strings, such as String str= "AAA"; , str refers to the object in the pool, and the second is to use a string constructor with a string argument, and when the passed parameter value is in the form of a string constant, not a variable, that is, a string Str=new string ("AAA"); Instead of defining string s = "aaa," and then using string Str=new string (s) to create the object, new string (s), only one object is created, but if it does not exist in the pool, we can use the Intern method to put it into the pool. Of course, the assumption is that these string objects do not exist in the pool.
In fact, it is only a matter of time before the pool is found, that is, when you use literal constant strings directly. The two kinds of timing mentioned above are essentially the direct use of literal strings and putting them into the pool.

There are multiple references to stacks in the JVM, and here's a summary of their respective roles:
The stack is used to hold a reference to the base type and object, and the base type will see if it already exists in the stack before it is created.
String inside a string array to store strings, so it can be considered as char[] equivalent, string a= "abc", first in the heap to create an object, and then to the stack to find char[] whether there is a point to the address, none in the stack to create an array.
New comes out in the heap, where the heap is used to store objects.


How many objects did the string create?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.