String是我们在开发中使用频率极高的一种引用类型,大家都知道String是不可变的,看下列代码:
public static void main(String[] args) { String s="hello"; System.out.println(s+"oo"); System.out.println(s); }
这个时候呢,就会产生临时变量来 存储hello000;我们Ctrl+String看看源码:
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 public String() { this.value = new char[0]; } public String(char value[]) { this.value = Arrays.copyOf(value, value.length); }
可见,String是通过char来实现的,另外
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); }
可以看到String中的许多方法在最后,return new String,那么就是新建了一个数组,而原值不被改变,有许多方法,就不一一举例了;
在来看看StringBuffer和StringBuilder,这两个都是可以改变的字符串;
这两个的区别看看源码很容易就懂得:
StingBuffer的方法用synchronized修饰,称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象;
可见StringBuffer线程安全的,那么就意味着StringBuffer的效率低于 StringBuilder;