A little understanding of the string class in Java __java

Source: Internet
Author: User

Recently in the review of Java, encountered some confusion about string type, after consulting some information is a little experience, remember.

First, look at the following code:

String a = "programming";
String b = new String ("Programming");
String C = "program" + "Ming";

System.out.println (A = = B);
System.out.println (A = = c);
System.out.println (A.equals (b));
System.out.println (A.equals (c));
System.out.println (a.intern () = = C.intern ());

What will the output of the above program be? The answer is:

False
True
True
True
True

For a literal constant of "programming", its value can be determined at compile time, so is also known as the compile-time constant, which is stored in a constant pool. Java Virtual Opportunities Ensure that there is only one object for a compile-time constant. For string constants of literal types (that is, strings such as "programming"), when you connect string constants of multiple literal types using the string connector "+", the compilation period is optimized at compile time without having to wait until the runtime to determine their values. Remove the connectors directly, combine them into a literal constant, and ensure that the object of the literal constant is only one in the constant pool. So string A is equivalent to string C in the above code. For string variable B, because it is an object generated using the new operator, it points to an object in the heap that is naturally not the same object as the "programming" in the constant pool.

For the last output statement, the Intern method of the string class is invoked. Let's take a look at the introduction in Javaapi: intern

Public String Intern ()
Returns a normalized representation of a string object. An initially empty string pool that is maintained privately by the class string.
When the Intern method is invoked, the string in the pool is returned if the pool already contains a string that is equal to this string object (determined by the Equals method). Otherwise, this string object is added to the pool and a reference to this string object is returned.
It follows the following rule: for any two strings s and T, s.intern () = = T.intern () is true if and only if S.equals (t) is true.
All literal strings and string assignment constant expressions are manipulated using the Intern method.

So variable A and variable C call the object returned by the Intern method the same.

OK, read the above explanation, and then look at a code to see if you can correctly understand:

String s = "a" + "B" + "C" + "D";

Q, how many string objects will be created after the above code is executed? The answer is to create only 1. Think about why.

Second, look at the following code:

String a = "HelloWorld";
Final String B = "Hello";
String c = "Hello";
String d = "world";
String e = "Hello" + "world";

String CD = c + D;
String F = b + D;
String g = B + "World";
String h = c + "World";

System.out.println (A = = e);
System.out.println (A = = CD);
System.out.println (A = = f);
System.out.println (A = = g);
System.out.println (A = = h);

What does the above program output? The answer is:

True
False
False
True
False

We have already explained the result of the code line 12. But why the next few lines of output are so strange. Here we have to distinguish between open literals the difference in string operations between a constant string and a string variable.
Let's take a look at the bytecode file in the code above to find out what the JVM is doing.

String HelloWorld//corresponds to the first line of the above code. Hello//second line of string Hello//Third line string World//Line fourth string HelloWorld//Five//above is a few string variables
Copy, remember the above API said.

"All literal strings and string assignment constant expressions are manipulated using the Intern method"///So the above string variable refers directly to the object in the constant pool.
Class Java/lang/stringbuilder//Create a StringBuilder object. Method Java/lang/stringbuilder. "
<init>:() V//Add string variable C, D to StringBuilder.
Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
Method java/lang/stringbuilder.tostring: () ljava/lang/string;

The above piece corresponds to a string cd = C + D; this code.
Class Java/lang/stringbuilder//below this piece corresponds to String f = b + D; Method Java/lang/stringbuilder. "
<init> ":() V String Hello//Because B is the final type, that is, the constant, so take the object directly from the constant pool.
Although it is a literal constant, it is connected to the string variable d, so it is also placed in the StringBuilder object.
Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder; Method java/lang/Stringbuilder.tostring: () ljava/lang/string;
String HelloWorld//This sentence corresponds to string g = B + "World";

Because B is a constant, "world" is a literal constant, so just remove "+" and connect it.
The following corresponds to the last sentence string h = c + "World";
It also generates a StringBuilder and then adds a variable and a literal constant to the StringBuilder. Class Java/lang/stringbuilder method Java/lang/stringbuilder. "
<init> ":() V method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;
String World Method Java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder; Method java/lang/stringbuilder.tostring: () ljava/lang/string;

The above analysis basically makes sense of what the JVM does, and it's clear why the code outputs the results above.
The first two concepts are divided: the string variable (string a) and the literal constant ("HelloWorld").
Simply put, for concatenation operations that have only literal constants, the JVM connects them directly together and puts them in a constant pool as a unique constant object. Note that the final modifier is also a constant yo. For example, the final string b = "Hello" above, and constant B is also treated as a literal constant. Because literal constants can determine their values during compilation, the compilation period optimizes the code, which means that you do not have to wait until the runtime to get their values and put them in a constant pool. So the above a, E, and G are the same, all of which refer to the same unique object in the constant pool.
For concatenation of string variables (note a connection operation), such as a string cd = C + d or string h = C + "World", the JVM takes the action of a StringBuilder object, and then adds both of the required connections to the string The Builder object. Operations are generally as follows:

StringBuilder builder = new StringBuilder ();
Builder.append (c);
Builder.append (d);
cd = Builder.tostring ();

Let's look at the ToString () method of the StringBuilder class.

Public String toString () {
//Create a copy, don ' t share the array return
new String (value, 0, count);
}

See, a new string object was created. So, it's not the same as the literal constant object.

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.