Thinking of creating a String object in the Java written test

Source: Internet
Author: User

The topic is such that the following ones generate a new string object ()

A, String s = new string ();

B, String s = new String ("A");

C, String s = "";

D, String s = "A". Intern ();

E, String s = (string) String.class.newInstance ();

From a sudden look at this topic, feeling a, B, C, D, E are all right, so what exactly choose that?

Analysis:

A: An object named S is created

B: You may have created two objects, one is an S object and the other is a object in a constant pool

C: A reference to an empty string was created

D: "A". What the hell is intern? Let's analyze it in detail:

Do not say anything first, first look at the following example of the introduction:

New New String ("Calvin");       = = str1)   ;

I JDK version 1.8, the output is:

true  true  

Then add a line of code to the example above:

String str2 = "Seucalvin"; // New line of code, remaining unchanged   New New String ("Calvin");       = = str1)   ;
Run again, the result is:
false  false

is not feeling puzzled, the new definition of str2 and str1 do not have a half-gross money relationship, how can affect the output of the str1? Actually this is the intern () method to make the ghost! After reading this article, you will understand. O (∩_∩) o

To tell you the truth, I was going to summarize an article on the memory leak of Android, read a lot of information, and found that I had to speak from the Java oom, the Java Oom has to talk about the Java Virtual Machine architecture. If you do not know the JVM, you can view this Jvm--java virtual machine architecture. (This article has been modified by me n times, the personal feeling is quite comprehensive clear, every time there will be a new understanding.) )

Also described in the JVM architecture article, there is a constant pool in the method area of the data area in the JVM runtime, but it is found that the constant pool is placed in heap space after JDK1.6, so the difference in the constant pool position affects the performance of the string's intern () method. In-depth understanding of the discovery is still worth writing down the record.

1. Why introduce the Intern () method

The Intern () method is designed to reuse a string object to save memory consumption. That may be a bit abstract, so use examples to prove it.

Static Final intMAX = 100000; Static Finalstring[] arr =NewString[max];  Public Static voidMain (string[] args)throwsException {//random assignment of an integer array of length 10integer[] Sample =NewInteger[10]; Random Random=NewRandom (1000);  for(inti = 0; i < sample.length; i++) {Sample[i]=Random.nextint (); }      //Log program start time    Longt =System.currenttimemillis (); //use/Do not use the Intern method to assign 100,000 string values from 10 numbers in an integer array         for(inti = 0; i < MAX; i++) {Arr[i]=NewString (string.valueof (sample[i%sample.length])); //Arr[i] = new String (string.valueof (sample[i% sample.length]). Intern (); } System.out.println ((System.currenttimemillis ()-T) + "MS");  System.GC (); }  

This example is also relatively simple to prove that using intern () consumes less memory than using intern ().

Define an integer array of length 10 and assign them randomly, assigning values to string objects of length 100,000 through A For loop, all from the integer array. In both cases, you can set the JVM startup parameter to-agentlib:hprof=heap=dump,format=b via window---> Preferences----and installed JREs. Place the hprof after the program has finished running in the project directory. The Hprof file is then viewed through the mat plugin.
The results of two experiments were as follows:

From the running results, the Intern () is not used, Cheng is 101,762 string objects, and when the Intern () method is used, the program generates only 1772 string objects. Nature also proves the conclusion that intern () saves memory.

Careful classmates will find that the program run time has increased after using the Intern () method. This is because the time taken for the intern () operation to occur in the program each time the new string is used, but not using intern () takes up memory space and causes the GC to be much longer than this time.

2. In-depth understanding of the intern () approach

After JDK1.7, the constant pool is put into the heap space, which causes the function of the intern () function to be different, how to vary the method, and look at the following code:

New String ("1");  S.intern ();   = "1";   = = s2)    ; New New String ("1");  S3.intern ();   = "one";   = = S4);  

The output is:

JDK1.6 and the following: falsefalse  JDK1.7 and above:falsetrue  

Then adjust the order of the above code 2.3 lines and 7.8 lines respectively.

New String ("1");   = "1";  S.intern ();   = = s2)    ; New New String ("1");   = "one";  S3.intern ();   = = S4);  

The output is:

JDK1.6 and the following: false false  JDK1.7 and above:falsefalse

The following is an analysis of the Intern () method based on the above code:

2.1 JDK1.6

All output in JDK1.6 is false, because JDK1.6 and previous versions, the constant pool is placed in the Perm area (in the method area), familiar with the JVM should know that this is completely separate from the heap area.

A string declared with quotation marks is generated directly in the string constant pool, and the new string object is placed in the heap space. So the memory address of the two is certainly not the same, even if the Intern () method is called, it is not affected. If you don't know the difference between the "= =" and equals () of the string class, you can see my blog post Java interview-the difference between equals and = = from the Java heap and stack angle.

The Intern () method works in JDK1.6 such as string s = new String ("Seu_calvin"), and then S.intern (), when the return value is the string "Seu_calvin", On the surface it looks as if this method is of little use. But in fact, in JDK1.6, it did a little trick: check if there is a string in the string pool that has "Seu_calvin" in it, return the string in the pool if it exists, and if it does not, the method adds "Seu_calvin" to the string pool and returns its reference. However, this is not the case in JDK1.7, which will be discussed later.  

2.2 JDK1.7

For JDK1.7 and above, we will discuss the above two pieces of code separately. Let's look at the first piece of code:

Then put the first piece of code for easy viewing:

New String ("1");  S.intern ();   = "1";   = = s2)    ; New New String ("1");  S3.intern ();   = "one";   = = S4);  

string s = newstring ("1"), resulting in a constant pool of "1" and a string object in the heap space.

S.intern (), the function of this line is that the S object goes to the constant pool to find that "1" already exists in the constant pool.

String s2 = "1", this line of code is to generate a S2 reference to the "1" object in the constant pool.

The result is a significantly different reference address for S and S2. Therefore, false is returned.

String s3 = new String ("1") + newstring ("1"), this line of code generates "1" in the string constant pool and generates the object that the S3 reference points to in the heap space (the content is "11"). Note that there is no "11" object in this constant-amount pool.

S3.intern (), which is a line of code that puts the "11" string in S3 into a string constant pool, where there is no "11" string in the constant pool, and JDK1.6 is to generate a "11" object directly in the constant pool.

However, in JDK1.7, there is no need to store another copy of the object in the constant pool, and you can directly store the references in the heap. This reference points directly to the object referenced by S3, which means that S3.intern () ==s3 returns True.

String S4 = "11", this line of code is directly to the constant pool created, but found that there is already this object, this is a reference to the S3 Reference object. So s3 = = S4 Returns True.

The second piece of code is continued below:

Then put the second piece of code for easy viewing:

New String ("1");   = "1";  S.intern ();   = = s2)    ; New New String ("1");   = "one";  S3.intern ();   = = S4);  

string s = newstring ("1"), resulting in a constant pool of "1" and a string object in the heap space.

String s2 = "1", this line of code is to generate a S2 reference to the "1" object in the constant pool, but the discovery already exists, then points directly to it.

S.intern (), this line here doesn't really work. Because "1" already exists.

The result is a significantly different reference address for S and S2. Therefore, false is returned.

String s3 = new String ("1") + newstring ("1"), this line of code generates "1" in the string constant pool and generates the object that the S3 reference points to in the heap space (the content is "11"). Note that there is no "11" object in this constant-amount pool.

String S4 = "11", this line of code will go directly to generate "11" in the constant pool.

S3.intern (), this line here doesn't really work. Because "11" already exists.

As a result, S3 and S4 have significantly different reference addresses. Therefore, false is returned.

3 Summary

Finally to do the ending. Now let's look at the introduction of the opening example, is it clear?

New New String ("Calvin");         = = str1)     ; = = "Seucalvin");  

Str1.intern () = = STR1 is the case in the example above, Str1.intern () finds that there is no "seucalvin" in the constant pool and therefore points to str1. When "Seucalvin" is created in a constant pool, it points directly to str1. Two all return true for granted.

So the second piece of code:

String str2 = "Seucalvin"; // New line of code, remaining unchanged   New New String ("Calvin");       = = str1)   ; = = "Seucalvin");   

Also very simple, str2 first created in the constant pool "Seucalvin", then Str1.intern () of course directly points to the STR2, you can go to verify that both of them are returned true. The back "Seucalvin" also points to str2. So no one took the str1 in the heap space, so they all returned false.

Reprint please specify the source http://blog.csdn.net/seu_calvin/article/details/52291082

From the above analysis, we can Know "A". Intern (); It is not necessary to create a string object, it may just fetch a reference to an A object.

E, the option is to produce an instance, and does not create a string object.

Reprint Please specify source: https://i.cnblogs.com/EditPosts.aspx?postid=9119698&update=1

Thinking of creating a String object in the Java written test

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.