String类对象的拼接操作:执行到s+="world"语句时,常量池会先创建"world"对象,再去创建"helloworld"对象,最后将"helloworld"对象的首地址赋给栈内存的s变量
StringBuilder构造方法:
StringBuilder添加和反转方法:
1 import java.util.Scanner; 2 public class test { 3 public static void main(String[] args) { 4 //创建对象 5 StringBuilder sb1=new StringBuilder(); 6 //连接 7 sb1.append("Hello"); //append方法返回对象本身 8 sb1.append("World"); 9 sb1.append(100); 10 System.out.println(sb1); //"HelloWorld100" 11 //链式编程 12 StringBuilder sb2=new StringBuilder(); 13 sb2.append("Hello").append("World").append("Java").append(100); 14 System.out.println(sb2); //"HelloWorldJava100" 15 //反转字符串 16 sb1.reverse(); 17 System.out.println(sb1); //"001dlroWolleH" 18 } 19 }
StringBuilder与String的相互转换
1 public class test { 2 public static void main(String[] args) { 3 //StringBuilder转换为String 4 StringBuilder sb1=new StringBuilder(); 5 sb1.append("hello"); 6 String s=sb1.toString(); 7 System.out.println(s); 8 //String转换为StringBuilder 9 StringBuilder sb2=new StringBuilder(s); 10 System.out.println(sb2); 11 } 12 }
原文地址:https://www.cnblogs.com/NiBosS/p/11965990.html
时间: 2024-10-14 13:52:55