String
字符串常量都存储在字符串常量池(StringTable)中
jdk7之前,字符串常量池存放在方法区.
jdk7及以后,字符串常量池存放在堆空间.
堆空间GC较频繁
// String的不可变性
对字符串变量重新赋值,拼接,replace方法
是在字符串常量池中新增有一个字符串,而不是对原有字符串进行修改
// 常用方法
boolean equals(Object anObject)
char charAt(int index)
int length()
String substring(int beginIndex,int endIndex)// 返回子串[beginIndex,endIndex)
String[] split(String regex)// 分割字符串
int indexOf(String str)// 返回指定字符串第一次出现的索引
boolean contains(CharSequence s)// 底层调用indexOf,存在子串返回true.集合类也有contains方法
public static void main(String[] args) {
String s1 = "hh";// 字符串常量池
String s2 = "hh";
System.out.println(s1 == s2); // true
// String的不可变性
s2 = "hj";
System.out.println(s1); // hh
}
// 在内存中创建了两个对象,一个是堆空间中new的,一个是字符串常量池中的字面量
String s = new String("hell");
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello" + "world";
String s5 = s1 + "world"; // 调用StringBuilder的toString,里面是new String()
String s6 = "hello" + s2;
String s7 = s1 + s2;// 变量 + 常量\变量 都会通过new的方式创建新的字符串
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//fasle
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
String s8 = s5.intern();//返回字符串常量池中字面量
System.out.println(s3 == s8);//true
StringBuffer和StringBuilder
StringBuffer和StringBuilder都继承自AbstractStringBuilder
// StringBuffer:可变字符序列;JDK1声明,线程安全,效率较低
// StringBuilder:可变字符序列;JDK5声明,线程不安全,效率较高
// 可变的意思是,可以在原有的基础上进行修改,而不是新造一个
StringBuilder存储字符串的数组大小默认会比字符串长度大,默认是16
不够用的时候会扩容
// StringBuilder转String
StringBuilder sb = new StringBuilder();
sb.append("[");
String s = sb.toString();
// String转StringBuilder
StringBuilder s = new StringBuilder(String s);