String和StrigBuilder的区别:String的内容是不可变的(开辟新的内存空间),StringBuilder的内容是可变的(对原来内存中的数据进行修改)
对字符串进行操作,每次拼接都会构建一个新的String对象,既耗时又浪费内存
String s = “hello”;
s += “world”;
堆内存 001:hello 002:world 003:helloworld
通过无参构造public StringBuilder() 创建一个空白可变字符串对象,不含有任何内容
StringBuilder sb = new StringBuilder();
System.out.println("sb:" + sb);//sb:
System.out.println("sb.length():" + sb.length());//0
StringBuilder的添加:通过public StringBuilder append()添加数据,并返回对象本身
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = sb.append(666);
System.out.println(sb);//666
sb.append("hello").append("world");
System.out.println(sb);//666helloworld
String和StrigBuilder的相互转换:
- StringBuilder转换为String
public String toString():通过toString()实现 - String转换为StringBuilder
public StringBuilder(String s):通过构造方法实现
StringBuilder sb = new StringBuilder("nice");
String s = sb.toString();