【回顾】String类的特点:
- String类对象有2种实例化方式:
|- 直接赋值:只开辟一块堆内存空间,可以自动入池;
|- 构造方法:开辟两块堆内存空间,不会自动入池,使用intern()手工入池;
- 任何一个字符串都是String类的匿名对象;
- 字符串一旦声明则不可改变,可以改变的是String类对象的引用;
String的内容不可改变。为此Java中有另外一个类——StringBuffer类(里面的内容可以改变)
String对象中使用 "+" 用于连接,但是在StringBuffer类中使用append进行追加;
- 方法:public StringBuffer append(数据类型 变量)
StringBuffer类:
范例:StringBuffer的基本使用
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("Hello").append("World").append("!!");
change(buf);
System.out.println(buf);
}
public static void change(StringBuffer temp) {
temp.append("\n").append("NI HAO!!");
}
}
StringBuffer 的内容是可以修改的,但是String的内容是不可修改的;
观察两个类的定义的结构发现,两者都是CharSequence接口的子类,如果以后发现CharSequence接口,可以知道只需要传递字符串即可;
虽然StringBuffer和String类有着共同的接口,但是2个类之间转换不可以直接转换;
- 将String变为StringBuffer类对象?
1、利用StringBuffer的构造方法:public StringBuffer(String str)
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello");
System.out.println(buf);
}
}
2、利用append()方法:public StringBuffer append(String str)
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("Hello");
System.out.println(buf);
}
}
- 将StringBuffer变为String类对象?
方法1:利用toString()方法可以将StringBuffer转换为String
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello");
String str = buf.toString();
System.out.println(str);
}
}
方法2:利用String类的构造方法:public Sting(StringBuffer buffer)
在String类中也提供有一个可以和StringBuffer比较的方法:public boolean contentEquals(StringBuffer sb)
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello");
System.out.println("Hello".contentEquals(buf));
}
}
StringBuffer 定义的一些与String类互补的方法:
- 字符串反转:public StringBuffer reverse()
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello");
System.out.println(buf.reverse());
}
}
- 在指定的索引位置增加数据:public StringBuffer insert(int offset, 数据类型 变量)
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello");
buf.insert(0, "World").insert(0,"NI HAO");
System.out.println(buf);
}
}
- 删除部分数据:public StringBuffer delete(int start, int end)
public class test {
public static void main(String args[]) throws Exception {
StringBuffer buf = new StringBuffer("Hello World NI HAO");
System.out.println(buf.delete(5, 11));
}
}
JDK1.5之后多了一个字符串操作类StringBuilder。
面试题:请解释String、StringBuffer、StringBuilder之间的区别?
- String的内容一旦声明不可改变,StringBuffer和StringBuilder声明的内容可以改变;
- StringBuffer类中提供的方法都是同步方法,属于安全的线程操作,而StringBuilder类中提供的方法都是异步方法,属于非安全的线程操作。