Thoroughly understand string constant pools and other related issues

Source: Internet
Author: User
Tags arithmetic
Objective:

In peacetime we use the string is generally used to get directly, very little in-depth to think about this knowledge , leading to others in the examination of our time, will ask the string str = new String ("123"); This line of code executes several objects, String str1= str + new String ("456"), where in this line of code is the str1 stored in memory, heap or string constant area (method area)? Will put our questions speechless , haha haha, in fact, is not the level of problems, is that we can usually carefully summarize the problem, the following on the detailed summary of such issues;

First, the easy to confuse and be asked silly a few questions categorized summary: [did not read the answer to this article, all correct answers, please leave a message, I am concerned about you]

Question 1:

New String ("1");    Str1.intern ();     = "1";     = = str2);  The result is false or true?     New New String ("2");    T3.intern ();     = "a";     = = STR4); The result is false or true?

Question 2:

String str1 = "AAA";   = "BBB";   = "AAABBB";   = str1 + str2;   = "AAA" + "BBB";   // false or True  // true or False  System.out.println (STR3 = = STR5); // true or False

Question 3:

New String ("2"= "2"==newnew String ("2" = "T4" = = =); False or True

Question 4:

    Integer a = 1;     = 2;     = 3;     = 3;     = 321;     = 321;     = 3L;     = = d)    ; = = f)    ; = = (A + b));    System.out.println (C.equals (a+b));     = = (A + b))    ; + b));

Second, the Knowledge reserve

In the process of answering these four questions, we first say a few knowledge, it is very important:

1.intern () function

The function of intern functions is to enter the corresponding symbolic constants into special processing, before 1.6 and 1.7 have different processing;

First Look at 1.6:

In 1.6, intern is the first to determine whether a string constant is in the string constant pool, if there is a direct return of the constant, if not found, the string constant is added to the string constant area, that is, in the string constant area to establish the constant;

  In 1.7:

In 1.7, intern is the first to determine whether a string constant is in the string constant pool, if there is a direct return of the constant, if not found, indicating that the string constant in the heap, processing is to add a reference to the heap area of the object in the string constant pool, What others get is a reference to the string constant that actually exists in the heap; "Thanks for the correction of the netizen, it is understood that the string object in the heap area is added to the reference, in fact, the string object that calls the method is either in the heap area or in the constant pool.

2. Constant pool Classification "understandable" 2.1 class file Constant pool

In the class file, in addition to the version "high version can load low version", fields, methods, interfaces and other descriptive information, there is also a message is Chang (Constant Pool Table) "is not loaded into memory at this time, that is, in the file", for storing the various literal and symbolic references generated during the compilation period .

The following is a description of literal and symbolic references
Literal quantity
Literals are similar to the constants we normally say, mainly including:

    1. Text string: A string that we can see in the code, such as String a = "AA". where "AA" is the literal amount.
    2. A variable that is final modified.

Symbol reference
The main include the following constants:

    1. Classes and interfaces and fully qualified names: for example, for the class String, its fully qualified name is java/lang/string.
    2. Field name and descriptor: the so-called field is a variable declared in a class or interface, including class-level variables (static) and instance-level variables.
    3. The name and descriptor of the method. The so-called descriptor is equivalent to the parameter type of the method + the return value type .
2.2 Running a constant-rate pool

We know that the class loader will load the corresponding class file, and the constant pool in the class file above will be in memory at the time the runtime pool in the method area is loaded. It is also important to note that the run-time-constant pool is globally shared, and multiple classes share a single run-time-constant pool. and there is only one copy of the constant pool in the class file where multiple identical strings are running.
Note the run-time constant pool exists in the method area .

2.3 String constant Pool

Look at the name. The string constant pool is used to hold the string , meaning that the literal string in the constant pool enters the string constant pool when the class loads.
What is the relationship between a string constant pool and a run-time pool? Above, we say that the literal in the constant pool will be in the class load backward into the run-time constant pool, where the literal string is included, obviously from this text we can know that the string constant pool exists in the run-time pool. is also present in the method area .
But in Zhou Zhiming's deep Java virtual machine, it is said that when the JDK1.7, the string constant pool is moved out of the method area, transferred to the heap .
Then we can infer that, in the JDK1.7 and later versions, the run constant pool does not contain a string constant pool, the run-time pool exists in the method area, and the string constant pool exists in the heap .

3. Problem Resolution "Focus" 3.1 Problem 1 analysis
 tring str1 = new String ("1" ); 
  Parsing: First this line of code creates two objects, creates a "1" object in the constant pool before execution, and then executes the line code when the object of new one "1" is stored in the heap area, and then str1 points to the object in the heap area;
Str1.intern ();
Parse: The line code first to see whether the "1" string exists in a constant pool, where there is a direct return of the constant, there is no reference to accept him, "if it does not exist in the jdk1.6 in the constant pool will be established in the constant, after jdk1.7 will be in the heap reference to the object in the constant pool"  
String str2 = "1" ;
Parse: At this point "1" already exists in the constant pool, str2 points to the object in the constant pool;

System.out.println (str1 = = str2); The result is false or true?  
Parse: str1 The object that points to the heap area, str2 points to the object in the constant pool, two references to different addresses, enter false, String STR3 = new String ("2") + New String ("2" );
Parsing: The underlying execution of this line of code is to first use StringBuffer's Append method to Stitch "2" and "2" together, then call the ToString method new out "22", so that the "22" string is created in the heap area;
T3.intern ();
Parse: The string constant pool does not have "22" when this line of code executes, so "22" is created in jdk1.6 in the string constant pool, and in jdk1.7 The reference to the object in the heap is then placed in a constant pool;
    String STR4 = "n";
Parsing: At this point the STR4 in the jdk1.6 will point to the method area, and in the jdk1,7 will point to the heap area;
System.out.println (STR3 = = STR4); The result is false or true?
Parsing: It is obvious that false in jdk1.6 is true in jdk1.7;
3.2 Problem 2 parsing
String str1 = "AAA";
Analysis: str1 points to the method area;
String str2 = "BBB";
Parse: str2 point to Method area
String STR3 = "AAABBB";
Parse: Str3 point to Method area
String STR4 = str1 + str2;
Parsing: This line of code above has already said the principle. STR4 pointing to the heap area
String STR5 = "AAA" + "BBB";
Parsing: The line code highlights that the JVM has optimized processing, that is, the two string constants are spliced during the compile phase, that is, "aaabbb"; so he is in the method area;
System.out.println (STR3 = = STR4); False or True
Parsing: Obviously false, a point to the heap a point to the method area
System.out.println (STR3 = = Str4.intern ()); True or False
Parse: jdk1.6 in Str4.intern will put "aaabbb" in the method area, after 1.7 in the heap area, so in 1.6 will be true but in 1.7 is false
System.out.println (STR3 = = STR5);//True or False
Parsing: All point to the string constant area, the string long constant area in the method area, the same string exists only one copy, in fact, this place is expanding, because the method area string constant is shared, when two threads share this string, if a thread change what would it be like? In fact, this scenario is thread-safe, and the JVM will change the string constants
Re-creating a process in a string constant pool to ensure thread safety

3.3 Problem 3 parsing
Tring T1 = new String ("2");
Parse: Created two objects, T1 point to Heap area
String t2 = "2";
Parse: T2 point to string constant pool
T1.intern ();
Parse: string constant pool already exists this string, return directly;
System.out.println (t1 = = t2);//false or True parsing: obviously false
string t3 = new String ("2") + New String ("2");
Parsing: Process with problem 1 T3 point to heap area
String T4 = "n";
Resolution: T4 in 1.6 and 1.7 point to different t3.intern ();
Parse: string constant in the pool that already exists for the string to return directly
System.out.println (T3 = = T4); False or True
Resolution: It is obviously false pointing to a different memory area
3.4 Problem 4 parsing

There is a point of knowledge in this place. May be a blind spot, this time to thoroughly remember "

(1). There is a constant pool of Java basic types encapsulating classes in memory. These classes include Byte, short, Integer, Long, Character, Boolean. It is important to note that the two classes of float and double do not have a corresponding constant pool.


(2). The object of the wrapper class for the above 5 integer types is scoped, and the scope exists in the -128~127 in a constant pool, and outside the range is allocated in the heap area.


(3). In the Zhou Zhiming of the virtual machine there is such a sentence: packaging class
the "= =" Runner does not automatically unboxing without encountering arithmetic operations , and their Equals () method does not handle the relationship of the data type, in layman's words, if there are arithmetic operations on both sides of the "= =", then the automatic unpacking and data type conversion processing, The comparison is numerical and other unequal energy.


(4). The Equals method of long will first determine if it is a long type.


(5). Either integer or long, their equals method compares the values.


System.out.println (c = = d).
Parsing: Because of the function of the constant pool, C and D point to the same object (note that at this time = = comparison is the object, that is, the address, not the value). therefore true


System.out.println (E = = f).
Because 321 exceeds 127, the constant pool loses its function, so the E and F values are the same, but not the same object, which is false.


System.out.println (c = = (A+b)).
at this point = = There are arithmetic operations on both sides, unpacking is done, so at this time the value is compared, not the object . Therefore, it is true.


System.out.println (C.equals (a+b))
The values of C and a+b are equal to true.


SYSTEM.OUT.PIRNLN (g = = (A + b))
Because the = = has arithmetic operations on both sides, the comparison is numeric and therefore true.


System.out.println (G.equals (a+b)).
A long type of equal in comparison is the time, will first determine whether A+B is a long type, obviously a+b is not, so false

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.