interview Experience, I believe that we are often asked the difference between the three, speaking of string I believe that most people will say: "String is immutable, final modified", you will see the interviewer slightly wretched smile, and then asked: "The final modified class is immutable, That StringBuilder and StringBuffer are not final modified? "
1. First, say 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 value is used for character storage. */ private final char Valu E[]; /** 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;
You can see the member variables defined by string value and hash, where value is an array of bytes, and it is the final decoration , which is the key of the string immutable;
JDK1.7 partial annotations of string
The Java language provides special support for the string * concatenation operator (+), and for conversion of * other OB Jects to Strings. String concatenation is implemented * through the <code>StringBuilder</code> (or <code>stringbuffer </code>) * Class and its <code>append</code> method. * String conversions is implemented through the method * <CODE>TOSTRING</CODE>, defined by <code>object </code> * Inherited by all classes in Java. For additional information on * string concatenation and conversion, see Gosling, Joy, and Steele, * <i>the Java Lan Guage Specification</i>.
The above explains that Java provides special support for string, for example: string A= "a"; String b= "B"; When you perform a string c=a+b operation, you are actually creating a StringBuilder object, then stitching through apend (), and finally calling TOSTIRNG () to generate a new object to C.
A string that provides a way to modify the content is ultimately called New string (). Look at Some of the annotations of string
/** * The <code>String</code> class represents character strings. All * strings literals in Java programs, such as <code> "abc" </CODE>, is * implemented as instances of this CLA SS. * <p> * 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. For example: * <p><blockquote><pre> * String str = "abc"; * </pre></blockquote><p& Gt * is equivalent to: * <p><blockquote><pre> * char data[] = {' A ', ' B ', ' C '}; * String str = new S Tring (data); * </pre></blockquote><p> * Here is some more examples of what strings can be used:
Here a string str = "ABC" is defined, equivalent to char data[] = {' A ', ' B ', ' C '}; String str = new string (data);
Another look at a substring () method of the source code
/** * Returns A new string is a substring of the this string. The * substring begins at the specified <code>beginIndex</code>, extends to the character at Inde x <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" * "SM Iles ". Substring (1, 5) returns" Mile "* </pre></blockquote> * * @param beginindex the Beginn ing 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< /code> object, or * <code>beginindex</code> is larger than * <CODE>ENDINDEX</CODE>. */public String substring (int beginindex, int endIndex) {if (Beginindex < 0) {throw new Stringi Ndexoutofboundsexception (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 the definition of a variable str= "Hello World", is to allocate an object in memory new String ("Hello World"), when you modify str= "Hello Nimei", the variable points back to the new allocated in memory String ("Hello Nimei"); The original in-memory new String ("Hello World") is still there, unchanged, waiting for garbage collection. Is there really no way to modify the value in the new String ("Hello World") object without re-re-new it in memory? Let's take a look at an example.
It turns out that reflection can modify the contents of a string object, and reflection 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 * * Public Final class StringBuffer extends Abstractstringbuilder implements Java.io.Serializable, charsequence{/** use Ser Ialversionuid from JDK 1.0.2 for interoperability */static final long serialversionuid = 3388685877147921107L; /** * Constructs a string buffer with no characters in it and an * initial capacity of characters. */Public StringBuffer () {super (16); }/** * Constructs a string buffer with no characters in it and * the specified initial capacity. * * @param capacity the initial capacity. * @exception Negativearraysizeexception if the <code>capacity</code> * argument are less th an <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 String Buffer (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, charsequence{/ * * Use SERIALVERSIONUID for interoperability */static final long serialversionuid = 4383685877147921099L; /** * Constructs a string builder with no characters in it and an * initial capacity of characters. */Public StringBuilder () {super (16); }/** * Constructs a string builder with no characters in it and an * initial capacity specified by the <cod e>capacity</code> argument. * * @param capacity the initial capacity. * @throws Negativearraysizeexception if the <code>capacity</code> * argument are less th an <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 String Builder (String str) {super (Str.length () + 16); Append (str); }
StringBuffer and StringBuilder This part of the source code is basically the same, the constructor initialization size is 16, are inherited Abstractstringbuilder.
Look at the source code for the Abstractstringbuilder definition member variable
/** * A Mutable sequence of characters. * <p> * Implements a modifiable string. At contains some * particular sequence of characters, but the length and content of the * sequence CA n be changed through certain method calls. * * @author Michael McCloskey * @author Martin Buchholz * @author ULF zibis * @since 1.5 */abstract C Lass Abstractstringbuilder implements Appendable, charsequence {/** * 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. */abstractstringbuilder (int capacity) {value = new char[capacity]; }
the variable value defined in Abstractstringbuilder is a byte array, and the string's value is final modified 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 compared to StringBuffer, StringBuilder, and each modification of string is a new object in memory, and StringBuffer, StringBuilder is not used, and provides a certain caching function, the default size of 16 byte array, the default array length, the expansion is the length of the original byte array *2+2.
2). StringBuffer and StringBuilder, StringBuffer is synchronized, is thread-safe, and StringBuilder is non-thread-safe, single-threaded performance is a bit better When using StringBuffer and StringBuilder, it is possible to make the code more efficient by considering the initialization size and the number of expansions.
Java face question String,stringbuilder,stringbuffer