String, StringBuffer, StringBuilder class definitions

StringBuffer, StringBuilder, StringBuffer, StringBuilder

  • String
public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence
Copy the code
/**
 * A <tt>CharSequence</tt> is a readable sequence of <code>char</code> values. This
 * interface provides uniform, read-only access to many different kinds of
 * <code>char</code> sequences.
 * A <code>char</code> value represents a character in the <i>Basic
 * Multilingual Plane (BMP)</i> or a surrogate. Refer to <a
 * href="Character.html#unicode">Unicode Character Representation</a> for details.
 *
 * <p> This interface does not refine the general contracts of the {@link
 * java.lang.Object#equals(java.lang.Object) equals} and {@link
 * java.lang.Object#hashCode() hashCode} methods.  The result of comparing two
 * objects that implement <tt>CharSequence</tt> is therefore, in general,
 * undefined.  Each object may be implemented by a different class, and there
 * is no guarantee that each class will be capable of testing its instances
 * for equality with those of the other.  It is therefore inappropriate to use
 * arbitrary <tt>CharSequence</tt> instances as elements in a set or as keys in
 * a map. </p>
 */
public interface CharSequence 
Copy the code
  • StringBuffer
public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable.CharSequence
Copy the code
/** * A mutable sequence of characters. * 

* Implements a modifiable string. At any point in time it contains some * particular sequence of characters, but the length and content of the * sequence can be changed through certain method calls. */

abstract class AbstractStringBuilder implements Appendable.CharSequence Copy the code
/** * An object to which <tt>char</tt> sequences and values can be appended. The * <tt>Appendable</tt> interface must be  implemented by any class whose * instances are intended to receive formatted output from a {@link* java.util.Formatter}. * * <p> The characters to be appended should be valid Unicode characters as * described in <a href="Character.html#unicode">Unicode Character * Representation</a>. Note that supplementary characters may be composed  of * multiple 16-bit <tt>char</tt> values. * <p> Appendables are not necessarily safe for multithreaded access. Thread * safety is the responsibility of classes that extend and implement this * interface. * <p> Since this interface may be implemented by existing classes * with different styles of error handling there is no guarantee that * errors will be propagated to the invoker. */
public interface Appendable
Copy the code
  • StringBuilder
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable.CharSequence
Copy the code

String, StringBuffer, and StringBuilder all implement Serializable interface. The other implementation relationships are as follows:Here’s an explanation of some of the classes involved in the figure above:

The name of the class explain
AbstractStringBuilder This abstract class is the direct parent of StringBuilder and StringBuffer and implements modifiable strings. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed by some method calls.
Appendable interface Define ‘rules’ for string addition (append() method)
CharSequence interface Is a readable sequence of char values. This interface provides unified read-only access to many different types of datacharSequence.

The difference between a

Since StringBuilder and StringBuffer inherit AbstractStringBuilder, objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects; The value of a String is immutable, and every operation on a String generates a new String, which is inefficient and wastes a lot of memory.

Constructor of String, StringBuffer, StringBuilder

  • String

Reference: from the source analysis of String class common methods

  • StringBuffer
	public StringBuffer(a) {
        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}
     *               argument is less than {@code0}. * /
    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} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string buffer that contains the same characters
     * as the specified {@code CharSequence}. The initial capacity of
     * the string buffer is {@code 16} plus the length of the
     * {@code CharSequence} argument.
     * <p>
     * If the length of the specified {@code CharSequence} is
     * less than or equal to zero, then an empty buffer of capacity
     * {@code 16} is returned.
     *
     * @param      seq   the sequence to copy.
     * @since1.5 * /
    public StringBuffer(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
Copy the code
  • StringBuilder
/** * Constructs a string builder with no characters in it and an * initial capacity of 16 characters. */
    public StringBuilder(a) {
        super(16);
    }

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity specified by the {@code capacity} argument.
     *
     * @param      capacity  the initial capacity.
     * @throws     NegativeArraySizeException  if the {@code capacity}
     *               argument is less than {@code0}. * /
    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} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters
     * as the specified {@code CharSequence}. The initial capacity of
     * the string builder is {@code 16} plus the length of the
     * {@code CharSequence} argument.
     *
     * @param      seq   the sequence to copy.
     */
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
Copy the code

The difference between the two

Each StringBuffer and StringBuilder object has a buffer size (== the initial size is 16==). If the string size does not exceed its capacity, no new capacity is allocated. If the string size exceeds its capacity, it is automatically increased.

StringBuffer, StringBuilder partial methods

  • StringBuffer
@Override
    public synchronized int length(a) {
        return count;
    }

    @Override
    public synchronized int capacity(a) {
        return value.length;
    }

    @Override
    public synchronized void ensureCapacity(int minimumCapacity) {
        super.ensureCapacity(minimumCapacity);
    }

    @Override
    public synchronized void trimToSize(a) {
        super.trimToSize();
    }

    / * * *@throws IndexOutOfBoundsException {@inheritDoc}
     * @see        #length()
     */
    @Override
    public synchronized void setLength(int newLength) {
        toStringCache = null;
        super.setLength(newLength);
    }

    / * * *@throws IndexOutOfBoundsException {@inheritDoc}
     * @see        #length()
     */
    @Override
    public synchronized char charAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }

    @Override
    public synchronized int codePointAt(int index) {
        return super.codePointAt(index);
    }

    @Override
    public synchronized int codePointBefore(int index) {
        return super.codePointBefore(index);
    }

    @Override
    public synchronized int codePointCount(int beginIndex, int endIndex) {
        return super.codePointCount(beginIndex, endIndex);
    }
Copy the code
  • StringBuilder
@Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

    / * * *@throws StringIndexOutOfBoundsException {@inheritDoc} * /
    @Override
    public StringBuilder delete(int start, int end) {
        super.delete(start, end);
        return this;
    }

    / * * *@throws StringIndexOutOfBoundsException {@inheritDoc} * /
    @Override
    public StringBuilder deleteCharAt(int index) {
        super.deleteCharAt(index);
        return this;
    }

    / * * *@throws StringIndexOutOfBoundsException {@inheritDoc} * /
    @Override
    public StringBuilder replace(int start, int end, String str) {
        super.replace(start, end, str);
        return this;
    }

    / * * *@throws StringIndexOutOfBoundsException {@inheritDoc} * /
    @Override
    public StringBuilder insert(int index, char[] str, int offset,
                                int len)
    {
        super.insert(index, str, offset, len);
        return this;
    }

    
    @Override
    public int indexOf(String str) {
        return super.indexOf(str);
    }

    @Override
    public StringBuilder reverse(a) {
        super.reverse();
        return this;
    }

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

    /**
     * Save the state of the {@code StringBuilder} instance to a stream
     * (that is, serialize it).
     *
     * @serialData the number of characters currently stored in the string
     *             builder ({@code int}), followed by the characters in the
     *             string builder ({@code char[]}).   The length of the
     *             {@code char} array may be greater than the number of
     *             characters currently stored in the string builder, in which
     *             case extra characters are ignored.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        s.defaultWriteObject();
        s.writeInt(count);
        s.writeObject(value);
    }

    /** * readObject is called to restore the state of the StringBuffer from * a stream. */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        count = s.readInt();
        value = (char[]) s.readObject();
    }
Copy the code

The difference between the three

Methods in StringBuffer are all qualified with the synchronized keyword, but StringBuilder is not, so StringBuffer threads are safe and StringBuilder threads are not.

conclusion

String StringBuffer StringBuilder
String values are immutable, and every operation on a String generates a new String, which is inefficient and wastes a lot of limited memory Objects of the StringBuffer class can be modified multiple times and no new unused objects are created. The buffer has a certain size (== initial size is 16==). When the string size does not exceed its capacity, no new capacity is allocated, and when the string size exceeds its capacity, its capacity is automatically increased. Objects of the StringBuilder class can be modified multiple times without creating new unused objects. They have a buffer size (== initial size is 16==). No new buffer is allocated when the string size does not exceed its capacity, and when the string size exceeds its capacity, it automatically increases its capacity.
Immutable classes The variable class The variable class
Thread safety Thread insecurity
Multithreaded operation string Single-thread manipulation strings

StringBuilder provides an API that is compatible with StringBuffer, but does not guarantee synchronization. StringBuilder is designed to be an easy replacement for StringBuffer when the StringBuffer is being used by a single thread. This class is preferred if possible, as it is faster than StringBuffer in most implementations. The approach is basically the same.