StringBuffer,这是一个看起来和String有亲缘关系的类,事实上,的确如此,但StringBuffer在包含String类所有基本功能的情况更适合使用在需要频繁操作字符串的场合。
首先,来看一句话
"对于String,字符串常量一旦声明则不可改变,而字符串对象则可以改变,但是改变的是其内存地址的指向"
这里看一个简单的例子:
String s="abc";//此时s指向对象new String("abc")
s="bcd"; //此时s指向new String("bcd"),原来指向对象被抛弃
此外,s=s+"hello";仍然表示指向了新对象new String("bcdhello"),为了存储新的对象中间JVM会自动生成一个BufferString。
StringBuffer中字符串的连接使用append()方法
public class StringBufferDemo01 {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer() ;
buf.append("hello") ;
buf.append(" ").append("world").append("!!!") ;
System.out.println(buf) ;
}
}
String无法被继承,因为使用了final定义。
String——>StringBuffer
public class StringBufferDemo02 {
<span style="white-space:pre"> </span>public static void main(String[] args) {
String s="hello";
<span style="white-space:pre"> </span>StringBuffer buf = new StringBuffer(str) ;
<span style="white-space:pre"> </span>System.out.println(buf) ;
<span style="white-space:pre"> </span>}
}
StringBuffer——>String
public class StringBufferDemo02 {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer() ;
buf.append("hello") ;
String str = buf.toString() ; // StringBuffer --> String
System.out.println(str) ;
}
}
StringBuffer中的三个常用方法
reverse() 字符串反转操作
replace(start,end,"str") 字符串指定部分替换操作
insert(pos,"str") 字符串指定位置插入字符串操作
以上三个方法String类不存在
这里我们再引入一个字符串类StringBuilder
推荐博客:http://blog.csdn.net/sunnyyoona/article/details/50370580