StringBuilder我们可以把其看成一个容器,是一个可变的字符串类,其StringBuilder对象中的内容是可变的
String | StringBuilder |
---|---|
String中的内容不可变 | StringBuilder:内容是可变的 |
StringBuilder通过append方法不断添加字符串到该容器中 |
package Socket_Thread.StringBuilderDemo;
/**
* @Author: 从南到北
* @Date: 2021/12/31/10:34
*/
public class StringBuilderDemo01 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println("sb:"+sb);
System.out.println("sb.length:"+sb.length());
StringBuilder sb2 = new StringBuilder("hello");
System.out.println("sb2:"+sb2);
System.out.println("sb2的长度:"+sb2.length());
}
}
StringBuilder中有两个常用的方法
append
任意类型要圈住,很重要
package Socket_Thread.StringBuilderDemo;
/**
* @Author: 从南到北
* @Date: 2021/12/31/10:34
*/
public class StringBuilderDemo01 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append("world");
sb.append("100");
System.out.println("sb:"+sb);
}
}
package Socket_Thread.StringBuilderDemo;
/**
* @Author: 从南到北
* @Date: 2021/12/31/10:34
*/
public class StringBuilderDemo01 {
public static void main(String[] args) {
//创建对象
StringBuilder sb = new StringBuilder();
//因为append方法返回的是对象本身,对象就可以调方法,所以,可以一直调用方法,即链式编程
//链式编程
sb.append("hello").append("world").append("java").append(100);
System.out.println("sb:" + sb);
//public StringBuilder reverse():返回相反的字符序列,直接把内容反转
sb.reverse();
System.out.println("sb:" + sb);
}
}