Java Face Test string,stringbuilder,stringbuffer__string

Source: Internet
Author: User
Tags array length garbage collection

In the interview experience, I believe that everyone is often asked the difference between the three, speaking of string, I believe most people will say, "String is immutable, final-modified," and you will see the interviewer slightly wretched, and then ask: "The final modified class is immutable, The StringBuilder and StringBuffer were not final-decorated. ”


1. First, string.

Look at the source code for the JDK1.7 string member variable

/**
 * @author  Lee Boynton
 * @author  Arthur van Hoff *
 @author  Martin Buchholz
 * @author  Ulf zibis
 * @see     java.lang.object#tostring ()
 * @see     java.lang.StringBuffer
 * @see     java.lang.StringBuilder
 * @see     java.nio.charset.Charset
 * @since   JDK1.0

* * Public final class String
    implements Java.io.Serializable, Comparable<string>, charsequence {
    /** the The value is used for character storage. *
    Private final char value[];

    /** Cache The hash code for the string *
    /private int hash;//Default to 0

    /** use serialversionuid from JDK 1. 0.2 for Interoperability * *
    private static final long serialversionuid = -6849794470754667710l;

You can see the member variable value and hash defined by string, where value is an array of bytes and final modification, which is the key point of string immutable;

partial annotation of JDK1.7 string

The Java language provides special support
 for the string * concatenation operator (+), and for conversion of
 * Other objects to strings. String concatenation is implemented
 * through the <code>StringBuilder</code> (or <code> stringbuffer</code>)
 * Class and its <code>append</code> method.
 * String conversions are implemented through the method
 * <code>tostring</code>., defined by <code>o Bject</code> and
 * inherited by all classes in Java. For additional information on
 * string concatenation and conversion, Gosling, Joy, and Steele,
 * <i>the Java Language Specification</i>.
It explains that Java provides special support for string, for example: string A= "a"; String b= "B"; when the string c=a+b operation is performed, it is actually creating a StringBuilder object, then stitching through apend (), and finally invoking TOSTIRNG () to generate a new object to C.

String provides a way to modify the content by calling the new string (). Look at some of the notes in string

/**
 * The <code>String</code> class represents character strings. All
 * Strings literals in Java programs, such as <code> "ABC" </CODE> are
 * implemented as instances of This class.
 * <p>
 * Strings are constant their values cannot is changed after they
 * are created. String buffers support mutable strings.
 * Because String objects are immutable they can be shared. For example:
 * <p><blockquote><pre>
 *     String str = "abc";
 * </pre></blockquote><p>
 * is equivalent to:
 * <p><blockquote><pre>
 *     char data[] = {' A ', ' B ', ' C '};
 *     String str = new string (data);
 * </pre></blockquote><p>
 * Here are some the examples of how strings can be used:

This defines a string str = "abc"; equivalent to char data[] = {' A ', ' B ', ' C '}; String str = new string (data);
To see a substring () method of the source code


/** * Returns A new string, is a substring the this string. The * substring begins at the specified <code>beginIndex</code> @ extends to the character at
     Dex <code>endindex-1</code>.
     * Thus The length of the substring is <code>endindex-beginindex</code>.  * <p> * Examples: * <blockquote><pre> * "Hamburger" substring (4, 8) returns "Urge" *  "Smiles". Substring (1, 5) returns "Mile" * </pre></blockquote> * * @param beginindex the
     Beginning index, inclusive.
     * @param endindex the ending index, exclusive.
     * @return the specified substring.
     * @exception Indexoutofboundsexception If the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of * this <code>string& Lt;/code> object, or *;code>beginindex</code> is larger than * &LT;CODE&GT;ENDINDEX&LT;/CODE&GT;. */public String substring (int beginindex, int endindex) {if (Beginindex < 0) {throw new Stri
        Ngindexoutofboundsexception (Beginindex);
        } if (Endindex > Value.length) {throw new stringindexoutofboundsexception (Endindex);
        int sublen = Endindex-beginindex;
        if (Sublen < 0) {throw new stringindexoutofboundsexception (Sublen); Return ((beginindex = 0) && (endindex = = value.length))?
    This:new String (value, Beginindex, Sublen); }


After reading these, you can clearly know that defining a variable str= "Hello World" is to allocate an object new String ("Hello World") in memory, and when you modify str= "Hello Nimei", the variable points back to the new assigned in memory. String ("Hello Nimei"); The original memory of the new String ("Hello World") is still there, unchanged, waiting for garbage collection. Is there really no way to change the value in the new String ("Hello World") object without restarting the new one in memory? Let's take a look at an example.



The reflection allows you to modify the contents of a string object, which is too powerful.


2.StringBuffer and StringBuilder


StringBuffer part of the source code

* @author Arthur van Hoff * @see Java.lang.StringBuilder * @see java.lang.String * @since JDK1.0/PU Blic Final class StringBuffer extends Abstractstringbuilder implements Java.io.Serializable, Charsequence {/ * * Use Serialversionuid from JDK 1.0.2 for interoperability/static final long Serialversionuid = 338868587714792110

    7L;
     /** * Constructs a string and no characters in it and a * initial capacity of characters.
    * * Public StringBuffer () {super (16);
     }/** * Constructs a string and no characters in it and * the specified initial capacity.
     * * @param capacity the initial capacity. * @exception Negativearraysizeexception if the <code>capacity</code> * argument is less t
     Han <code>0</code>
    * * Public stringbuffer (int capacity) {super (capacity); }/** * Constructs a string buffer inItialized to the contents of the * specified string.
     The initial capacity of the string buffer is * <code>16</code> plus the length of the string argument.
     * * @param str The initial contents of the buffer. * @exception NullPointerException if <code>str</code> is <code>null</code>/public stri
        Ngbuffer (String str) {super (Str.length () + 16);
    Append (str); }


StringBuilder part of the source code

* @author Michael McCloskey * @see Java.lang.StringBuffer * @see java.lang.String * @since 1 .5/Public final class StringBuilder extends Abstractstringbuilder implements Java.io.Serializable, Charsequenc

    e {/** Use SERIALVERSIONUID for interoperability/static final long serialversionuid = 4383685877147921099L;
     /** * Constructs a string builder with no characters in it and a * initial capacity of characters.
    * * Public StringBuilder () {super (16); }/** * Constructs a string builder with no characters in it and a * initial capacity
     ;code>capacity</code> argument.
     * * @param capacity the initial capacity. * @throws Negativearraysizeexception if the <code>capacity</code> * argument is less t
     Han <code>0</code>
   * * Public StringBuilder (int capacity) {super (capacity); /** * Constructs a string builder initialized to the contents of the * specified string.
     The initial capacity of the String builder is * <code>16</code> plus the length of the string argument.
     * * @param str The initial contents of the buffer. * @throws NullPointerException if <code>str</code> is <code>null</code>/public stri
        Ngbuilder (String str) {super (Str.length () + 16);
    Append (str); }


StringBuffer and StringBuilder This part of the source code basically the same, the constructor initialization size is 16, are inherited Abstractstringbuilder.


Look at the source code that defines member variables Abstractstringbuilder

/**
 * A mutable sequence of characters.
 * <p>
 * Implements a modifiable string. At any point in time it contains some
 * particular sequence of characters, but the length and content of the
 * seq Uence can be changed through certain method calls.
 *
 @author      Michael McCloskey
 * @author      Martin Buchholz *
 @author      Ulf zibis
 * @since       1.5 */
abstract class Abstractstringbuilder implements Appendable, charsequence {
    /**
     * the The value is used for character storage.
     * *
    char[] value;

    /** * The count is the number of
     characters used.
     *
    /int count;

    /**
     * This no-arg constructor are necessary for serialization of subclasses.
    * * Abstractstringbuilder () {
    }

    /** * Creates an abstractstringbuilder of the
     specified capacity.< c31/>*/
    abstractstringbuilder (int capacity) {
        value = new char[capacity];
    }


The value of the variable defined in Abstractstringbuilder is a byte array, and the value of string is final decorated, compared to the member variable value of string. So the contents of StringBuffer and Stringbuilde can be changed.


In contrast to the implementation of Stingbuffer and StringBuilder other details, take the Append () method as an example.

Public synchronized StringBuffer append (String str) {
        super.append (str);
        return this;
    }

  Public StringBuilder append (String str) {
        super.append (str);
        return this;
    }
The biggest difference between the two is: Stingbuffer all the methods of implementation are sychronized modified, StringBuilder is not.

Summary of 2.String, StringBuffer and StringBuilder
1. String is immutable than StringBuffer and StringBuilder, and every modification of string is a new object in memory, and StringBuffer, StringBuilder is not used, and provides a certain caching function, the default 16 byte array size, more than the default length of the array, then the expansion of the original byte array length *2+2.
2. Compared to StringBuffer and StringBuilder, StringBuffer is synchronized and thread-safe, while StringBuilder is not thread-safe and has a better performance in single-threaded conditions When using StringBuffer and StringBuilder, it is possible to consider the initialization size, less the number of expansions, and improve the efficiency of the Code.




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.