String类对象的拼接操作:执行到s+="world"语句时,常量池会先创建"world"对象,再去创建"helloworld"对象,最后将"helloworld"对象的首地址赋给栈内存的s变量

22.Java基础_StringBuilder类-LMLPHP

22.Java基础_StringBuilder类-LMLPHP

StringBuilder构造方法:

22.Java基础_StringBuilder类-LMLPHP

StringBuilder添加和反转方法:

22.Java基础_StringBuilder类-LMLPHP

 import java.util.Scanner;
public class test {
public static void main(String[] args) {
//创建对象
StringBuilder sb1=new StringBuilder();
//连接
sb1.append("Hello"); //append方法返回对象本身
sb1.append("World");
sb1.append(100);
System.out.println(sb1); //"HelloWorld100"
//链式编程
StringBuilder sb2=new StringBuilder();
sb2.append("Hello").append("World").append("Java").append(100);
System.out.println(sb2); //"HelloWorldJava100"
//反转字符串
sb1.reverse();
System.out.println(sb1); //"001dlroWolleH"
}
}

StringBuilder与String的相互转换

 public class test {
public static void main(String[] args) {
//StringBuilder转换为String
StringBuilder sb1=new StringBuilder();
sb1.append("hello");
String s=sb1.toString();
System.out.println(s);
//String转换为StringBuilder
StringBuilder sb2=new StringBuilder(s);
System.out.println(sb2);
}
}
05-12 07:50