JAVA基础 | String类 与 StringBuilder类 传递类型的区别(210117)
【String类】 值传递 (形参不影响实参)
【StringBuilder】 引用传递 (形参改变,实参也跟着改变)
【实例】
public class Test3 {
public static void a(String s) {
s=s+"!";
}
public static String d(String s) {
s=s+"??";
return s;
}
public static void b(StringBuilder s) {
s.append("!");
}
public static StringBuilder c(StringBuilder s) {
s.append("??");
return s;
}
public static void main(String[] args) {
String s="woc";
StringBuilder sb=new StringBuilder("woc");
Test3.a(s); //String为值传递
System.out.println(s);
Test3.d(s);
System.out.println(s);
Test3.b(sb); //StringBuilder为引用传递
System.out.println(sb);
Test3.c(sb);
System.out.println(sb);
}
}
//输出结果为:
woc
woc
woc!
woc!??
**【附】**StringBuilder常用方法实例
//StringBuilder基础方法实例(StringBuffer与之相同)
public class Test2 {
public static void main(String[] args) {
StringBuilder s=new StringBuilder("hello");
s.append("java"); //append()
System.out.println(s);
s.insert(5,","); //insert()
System.out.println(s);
s.append("nb");
System.out.println(s);
s.delete(10,12); //delete()
System.out.println(s);
s.reverse(); //reverse()
System.out.println(s);
s.reverse();
s.replace(6, 10, "Python"); //replace()
System.out.println(s);
}
}
//输出结果为:
hellojava
hello,java
hello,javanb
hello,java
avaj,olleh
hello,Python