面试题:
1.StringBuffer,String,StringBuilder的区别?
- A:String的内容是不可变的,而StringBuffer和StringBuilder的内容都是可变的
- B:在多线程的情况下,StringBuffer是同步的,数据安全的,但是效率相对较低;而StringBuilder是不同步的,数据不安全的,但是效率很高。
2.StringBuffer和数组的区别?
- 二者都可以看做是以个容器,装其他数据的容器。
- 但是,StringBuffer的数据最终是一个字符串数据
- 而数组可以放置多种数据,但必须是用同一种数据类型的
3.关于形式参数问题
- 基本类型:形式参数的改变不影响实际参数
- 引用类型:形式参数的改变直接影响实际参数
注意:
String作为参数传递,效果和基本类型作为参数传递是一样的。
示例代码如下:
public class StringBufferDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println(s1 + "----" + s2);//hello----world
change(s1,s2);
System.out.println(s1 + "----" + s2);//hello----world
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
System.out.println(sb1 + "----" + sb2);//hello----world
change(sb1,sb2);
System.out.println(sb1 + "----" + sb2);//hello----worldworld
}
public static void change(StringBuffer sb1, StringBuffer sb2) {
// TODO Auto-generated method stub
sb1 = sb2;
sb2.append(sb1);
}
public static void change(String s1, String s2) {
// TODO Auto-generated method stub
s1 = s2;
s2 = s1 + s2;
}
}
运行结果:
hello----world
hello----world
hello----world
hello----worldworld