Java Learning Note (1) String Common interview Knowledge Summary

Source: Internet
Author: User



Introduction (excerpt from Java source code)

Strings is constant; Their values cannot is changed after they is created. String buffers support mutable strings. Because String objects is immutable they can be shared.

From this sentence, we can know that the string is an immutable object, the value of the object can not be changed. Because of this, the string is thread-safe. Then StringBuffer is a mutable object.

"Question 1" What are immutable objects (immutable object), what are the benefits of immutable objects, under what circumstances should be used, or more specifically, why is the Java string class set to immutable type?

A: From the source of the string class, we can know that the immutable object is the object produced by the final keyword-decorated class, whose member variables are also final decorated, so that the class cannot be modified or inherited.

The benefits of immutable objects are mainly reflected in the following two aspects:

1. Immutable objects are thread-safe and can be used for multithreading. In multi-threaded communication, a variable is likely to be modified by multiple threads and is therefore not secure. Immutable objects can not be modified, security;

2. Immutable objects can increase the efficiency of the copy, and immutable means that only copy addresses are required for copying, which is highly efficient.

Public final class String    implements Java.io.Serializable, Comparable<string>, charsequence {    /** the Value is used for character storage. */    Private final char value[];    /** Cache The hash code for the string */    private int hash;//Default to 0    /** with serialversionuid from JDK 1.0. 2 for Interoperability */    private static final long serialversionuid = -6849794470754667710l; ...........................................}
Public final class StringBuffer    extends Abstractstringbuilder    implements Java.io.Serializable, charsequence{    /**     * A cache of the last value returned by toString. Cleared     * Whenever the StringBuffer is modified.     */    private transient char[] tostringcache;    /** use Serialversionuid from JDK 1.0.2 for interoperability */    static final long Serialversionuid = 33886858771479211 07L;}
And StringBuffer is the heir to Abstractstringbuilder.

Abstract class Abstractstringbuilder implements Appendable, charsequence {    /**     * The value is used for character Storage.     */    char[] value;    /** * The count is the number of     characters used.     */    int count;}
As you can see from the code above, the difference between string and StringBuffer, string is an immutable object, StringBuffer is immutable

What is the difference between a "question 2" string and a StringBuffer and a StringBuilder?

From question 1 We have seen one of the main differences: string is an immutable object, and StringBuffer is a mutable object. This also leads to a lot of other differences.

Look at the following two examples of string concatenation:

String str = new String ("Stanford  ");     str + = "lost!!";
StringBuffer str = new StringBuffer ("Stanford");     Str.append ("lost!!");
Q: Which is high efficiency?

At first glance, I really think that the first way is higher than the second way, but it is not. Let's look at the bytecode of the two programs.

0 new #7 < Class java.lang.string>3 DUP 4 ldc #2 <string "Stanford" >6 invokespecial #12 <method java.lang.String (java.la Ng. String) >9 astore_110 new #8 <class java.lang.stringbuffer>13 dup14 aload_115 invokestatic #23 <method java.la Ng. String valueOf (java.lang.Object) >18 invokespecial #13 <method java.lang.StringBuffer (java.lang.String) >21 LDC #1 <string "lost!!" >23 invokevirtual #15 <method java.lang.StringBuffer append (java.lang.String) >26 invokevirtual #22 <method Java.lang.String toString () >29 astore_1 
0 New #8 <class java.lang.stringbuffer>3 dup4 LDC #2 <string "Stanford" >6 invokespecial #13 <method java.l Ang. StringBuffer (java.lang.String) >9 astore_110 aload_1 One LDC #1 <string "lost!!" >13 invokevirtual #15 <method java.lang.StringBuffer append (java.lang.String) >16 pop
In the first way, because the string is an immutable object, in line 10th, it converts the string object to the StringBuffer object, and then the character is stitched up, converted to a string object at 29 rows, and returned to the user. In the second way, StringBuffer is a mutable object, stitching the string directly and returning. It is obvious from this that string is less efficient than stringbuffer on common string stitching problems.


Besides Stringbuilder,stringbuilder and StringBuffer are all mutable objects, what's the difference? A little comparison of the source code can be seen in stringbuffer most of the functions are with keywords: synchronized and StringBuilder do not. Therefore, the StringBuilder is more efficient than stringbuffer in a single thread, and StringBuffer can be used for multithreading.

"Question 3"differences in how string two is initialized

String str = new String ("abc");
String str = "ABC";

This is how we initialize the two kinds of string objects that are common to us, and what is the difference? First, let's look at a piece of code.

String str1 = new String ("abc"); The JVM creates a string object on the heap      //JVM the value "ABC" is not found in the strings pool, so    //creates a string object on the heap and adds a reference to the object to the strings pool    //There are two string objects   on this heap STIRNG str2 = "abc";      if (str1 = = str2) {            System.out.println ("str1 = = str2");    } else{            System.out.println ("str1! = str2");    }     The print result is str1! = str2 because they are two different objects on the heap       String STR3 = "abc";    At this point, the JVM discovers that there is already an "ABC" object in the string pool because "abc" equals "abc"    //So directly returns the object pointed to by str2 to Str3, meaning str2 and str3 are references     to the same object if (str2 = = str3) {            System.out.println ("str2 = = Str3");     } else{            System.out.println ("str2! = Str3");     }   
What is the output of the result?

Look at the code again.

String str1 = new String ("abc"); The JVM creates a string object on the heap     str1 = Str1.intern ();   The program explicitly puts str1 into the string pool, intern runs the process: First look at the string pool   //There is a reference to the "ABC" object, no, create a new object in the heap, and then add a reference to the new object to the   // The String pool. After executing the statement, the string object that the str1 originally pointed to has become a garbage object and is collected at any time   //by GC.     //At this point, the JVM discovers that there is already an "ABC" object in the string pool because "abc" equals "abc"   //So directly returns the object pointed to by STR1 to str2, which means str2 and str1 refer to the same object   . At this point, there is only one valid object on the heap.   stirng str2 = "abc";      if (str1 = = str2) {            System.out.println ("str1 = = str2");    } else{            System.out.println ("str1! = str2");    }   

What is the printing result?

This problem involves the Java memory model, the simple difference is:

The first initialization method immediately creates a string object on the pair, and then returns a reference to the object to the user. For the second, the JVM first determines the existence of the string object in the string pool. If so, returns an existing string object and, if not, re-creates the object in the heap, returning its reference to the user and adding the reference to the string pool. The first way is not to actively add objects to the string pool. So the first paragraph of the program output is

Str1! = STR2STR1 = = str2
So what's the output of the second program? The first way we talked about this is not to take the initiative to add the object to the string pool, but with an exception, calling the Intern () method manually will force a reference to the object to be added to the string pool. So the result of the second procedure is

STR1 = = str2
"Question 4"differences and linkages between String pool and const pool

Knowing the Java memory model, there is an area in Java memory called the method area. The method area is primarily used to store constants and static variables. The difference between a string pool and a const pool is simply that the string pool is part of the const pool, and the const pool consists of a number of constants, integers, and so on, and string pool is used exclusively to store string constants.

Not finished, continuous update ....




Java Learning Note (1) String Common interview Knowledge Summary

Related Article

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.