String 在java中用于表示字符串。String 对象的值是不可变的.
我们在平时有些时候采用String的拼接或者给一个变量重复赋值,表面上还是一个变量,实际上内存地址已经变化.
实际的String 是final定义的,是一个字符数据,是不可变的.(对于一个final变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改;如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。)
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
所以说,以下例子
String s="hell world";
s="java";
实际初始化变量s的时候,然后再对s进行赋值,实际是JVM重新创建了一个新的String对象.
假如对s变量一直不停的修改其对应的值,表面上只有一个变量,实际上JVM在不停的创建新对象,旧对象不断的回收死亡的过程,这样会使得JVM中产生大量的碎片,降低JVM的性能.
如果是在代码启动后,String对象不再修改重新赋值,那么可以考虑使用String,比如在代码中定义一些public static final String常量。如果需要在代码中频繁修改和赋值操作字符串对象具体内容,建议使用StringBuffer。
StringBuffer是字符串变量。StringBuffer不会产生String那样的问题:每一次修改就重新创建一个新的String对象。在某种程度上讲,StringBuffer内部维持一个可变长度的char数组来存放字符数据.
/**
* 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 = 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}
* argument is less than {@code 0}.
*/
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);
}