String
public final class String //被final修饰,不能被继承
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];//维护了一个字符数组,用来存储字符,且用final修饰
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** 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;
......
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
}
(1)String类是一个final类,因此其不能被继承。
(2)String维护了一个char[]数组,用来存储字符。且用final修饰,即不能被更改。
(3)String类中涉及对字符串修改的操作,都不是在原字符串上进行的,而是重新生成了一个新的String字符串即对原字符串没有影响。
StringBuffer & StringBuilder-----可变的字符串
(1)因为每次对String的修改操作都会重新生成一个String对象,因此非常浪费空间。这样就引入了StringBuffer和StringBuilder来处理这种变化的字符串。
(2)StringBuffer和StringBuilder是在原来字符串上进行修改,不会新产生对象。
(3)StringBuffer与StringBuilder的区别是,StringBuffer的方法用synchronized修饰了,是线程安全的。
String str = “abc”;String str = new String(“abc”)创建了几个对象
(1)String str = "abc"创建0个或者1个对象。—“abc”是字面量,存在于class文件中的常量池中。当类加载时存在与运行时常量池中。如果常量池中已经有这个字符串的字面量了,就不用再创建了。没有才创建。
(2)String str = new String(“abc”); new关键字,无论如何都会在堆中开辟空间,创建一个对象,然后返回地址给引用。因此肯定会在堆中创建一个对象。然后又有一个“abc”字面量,在类加载时需要在运行时常量池中构建这个字面量的(如果运行池常量池中没有),注意关于这个字面量,如果运行时常量池中已经存在,那么就不用创建了,如果没有才在运行时常量池中创建。