java面试题String,StringBuilder,StringBuffer

面试的经历中,相信大家都经常被问到这三者的区别,说到String我相信绝大多数的人都会说:"String是不可变的,final修饰的",你会看到面试官微微猥琐一笑,接着问到:“final修饰的类就是不可变的吗,那StringBuilder和StringBuffer不是final修饰的?”

1. 先来说说String

看下JDK1.7 String成员变量的源码

/**
 * @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 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;

可以看到String定义的成员变量value和hash,其中value是个字节数组,而且是final修饰,这个才是String不可变的关键点;

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>Object</code> and
 * inherited by all classes in Java. For additional information on
 * string concatenation and conversion, see Gosling, Joy, and Steele,
 * <i>The Java Language Specification</i>.

上面解释了java为String提供了特殊的支持,例如:String a="a";  String b="b" ;当执行String c=a+b操作时,实际上是创建一个StringBuilder对象,再通过apend()进行拼接,最后调用toStirng()生成一个新的对象给c。

String提供修改内容的方法最终都是调用new String()。看下 String的部分注解

/**
 * The <code>String</code> class represents character strings. All
 * string literals in Java programs, such as <code>"abc"</code>, are
 * implemented as instances of this class.
 * <p>
 * Strings are constant; their values cannot be 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 more examples of how strings can be used:

这里定义了一个String str = "abc";相当于char data[] = {‘a‘, ‘b‘, ‘c‘};String str = new String(data);

再来看一个substring()方法的源码

/**
     * Returns a new string that is a substring of this string. The
     * substring begins at the specified <code>beginIndex</code> and
     * extends to the character at index <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</code> object, or
     *             <code>beginIndex</code> is larger than
     *             <code>endIndex</code>.
     */
    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(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);
    }

看完这些,你可以清楚的知道定义一个变量str="hello world",则是在内存中分配一个对象new String("hello world"),当你修改str="hello nimei",变量重新指向内存中新分配的new String("hello nimei");原来内存中的new String("hello world")还在那里,没有改变,等待垃圾回收。难道真的没有办法修改new
String("hello world")对象中的值而不重新在内存中重新new一次吗?让我们来看看一个例子。

原来通过反射可以修改String对象中的内容,反射太强大了。

2.StringBuffer和StringBuilder

StringBuffer的部分源码

* @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 serialVersionUID 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 16 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 is less than <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 StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }

StringBuilder的部分源码

* @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 16 characters.
     */
    public StringBuilder() {
        super(16);
    }

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

StringBuffer和StringBuilder的这部分源码基本一样,构造函数初始化大小都为16,都是继承了AbstractStringBuilder。

看看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
 * sequence 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 value is used for character storage.
     */
    char[] value;

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

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

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

AbstractStringBuilder中定义的变量value,是个字节数组,和String的成员变量value相比,String的value是final修饰的,所以StringBuffer和StringBuilde的内容可以变。

在对比下StingBuffer和StringBuilder的实现其他细节,以append()方法为例。

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

两者最大的区别是:StingBuffer所有的实现的方法都是sychronized修饰的,StringBuilder则不是。

2.String、StringBuffer和StringBuilder的总结

1).  String和StringBuffer、StringBuilder相比,String是不可变的,String的每次修改操作都是在内存中重新new一个对象出来,而StringBuffer、StringBuilder则不用,并且提供了一定的缓存功能,默认16个字节数组的大小,超过默认的数组长度时,则扩容为原来字节数组的长度*2+2。

2).  StringBuffer和StringBuilder相比,StringBuffer是synchronized的,是线程安全的,而StringBuilder是非线程安全的,单线程情况下性能更好一点;使用StringBuffer和StringBuilder时,可以适当考虑下初始化大小,较少扩容的次数,提高代码的高效性。

时间: 2024-08-08 02:23:41

java面试题String,StringBuilder,StringBuffer的相关文章

Java基础之String,StringBuilder,StringBuffer

在创建字符串的时候总是习惯性的使用String str = "...";,str = str+"abcd";也有听说过StringBuffer,StringBuilder,但是压根就没想过要去了解过. String乍一看创建的很方便,其实在字符串比较多的时候或者说创建了多个字符串的时候就会出现很大的问题,因为String在新创建字符串的时候是在内存里面新开辟了一块内存去存储这个字符串,因为String是静态的,之所以我们看起来是动态的,那是因为JVM把我们欺骗了,在

Java之字符串String,StringBuffer,StringBuilder

总结的很全面,关于这三个类的操作. Java之字符串String,StringBuffer,StringBuilder

深刻理解Java中的String、StringBuffer和StringBuilder的区别

首先简单地来梳理一下Java中String.StringBuffer和StringBuilder各自的含义. 1.String类 首先,它是线程安全的,即可以用于多线程编程中: 其次,String类的对象是不可变的,即在定义时就确定了,类似String str="Hello";str+="Java";的语句其实是生成了新的对象,只是我们未察觉到而已.但是注意在大量的字符串新建对象时消耗就很可观,这时必须考虑采用StringBuffer或StringBuilder,否

Java基础----Java中的String和StringBuffer

String和StringBuffer String是一个特殊的对象,一旦被初始化,就不会被改变.()指的是abc 不是变量 s1. String s1="abc"; s1是一个类类型变量,"abc"是一个对象. String s2=new String("abc"); s1和s2的区别: s1在字符串常量池中创建了一个abc字符串 s2在堆中创建了两个对象一个是默认对象一个是字符串对象. ==和equals的区别 ==比较的是地址,equals

String StringBuilder StringBuffer 区别

String StringBuilder StringBuffer 区别: String 字符串常量 (可用于少量数据,变化不大的情况) 最慢 不可变类(每次改变都会引起创建新的String类) StringBuffer 字符串变量 线性安全(可多线程使用) 居于中间 可变类 StringBuilder 字符串变量 非线性安全(不支持并发操作,可单线程使用) 最快 可变类

Java中的String、StringBuffer和StringBuilder

任何语言都离不了字符串的处理.Java中处理字符串的三个类String.StringBuffer和StringBuilder.这三个到底有什么区别呢? 他们三个都是实现了CharSequence接口.但实现过程不一样. 其实他们的使用方法都很简单,这里看下StringBuilder的用法. public class TestStringBuffer{ public static void main(String args[]){ StringBuffer str=new StringBuffer

java中的String、StringBuffer、StringBuilder的区别

String.StringBuffer.StringBuilder都是java中的常用字符串类 ,下面来看看三者之间的异同. 一.可变与不可变: String:字符串常量,不可变.StringBuffer.StringBuilder为可变字符序列,是可变的. 二.是否多线程安全: String中的对象是不可变的,相当于常量,显然线程安全. StringBuffer:支持多线程安全. StringBuilder:不支持多线程安全. 三.执行效率: String.StringBuffer.Strin

深刻理解Java中的String、StringBuffer和StringBuilder的差别

声明:本博客为原创博客,未经同意.不得转载!小伙伴们假设是在别的地方看到的话,建议还是来csdn上看吧(链接为http://blog.csdn.net/bettarwang/article/details/26412497),看代码和提问.讨论都更方便. 首先简单地来梳理一下Java中String.StringBuffer和StringBuilder各自的含义. 1.String类 首先.它是线程安全的,即能够用于多线程编程中. 其次,String类的对象是不可变的,即在定义时就确定了,类似St

Java中的String、StringBuffer以及StringBuilder的用法和区别

String String的构造方式有n种(据说n==11),常见的例举一二: // 1 String s1 = "hello world"; // 2 String s2 = new String("hello world"); // 3 char[] a = {'h', 'e', 'l', 'l', 'o'}; String s3 = new String(a, 1, 3); // start length // 4 String s4 = "hell