String,StringBuffer,StringBuilder的一些面試題

/*
 * 面試題:
 * 1:String,StringBuffer,StringBuilder的區別?
 * A:String是內容不可變的,而StringBuffer,StringBuilder都是內容可變的。
 * B:StringBuffer是同步的,數據安全,效率低;StringBuilder是不同步的,數據不安全,效率高
 * 
 * 2:StringBuffer和數組的區別?
 * 二者都可以看出是一個容器,裝其他的數據。
 * 但是呢,StringBuffer的數據最終是一個字符串數據。
 * 而數組可以放置多種數據,但必須是同一種數據類型的。
 * 
 * 3:形式參數問題
 * String作爲參數傳遞
 * StringBuffer作爲參數傳遞 
 * 
 * 形式參數:
 * 		基本類型:形式參數的改變不影響實際參數
 * 		引用類型:形式參數的改變直接影響實際參數
 * 
 * 注意:
 * 		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) {
		sb1 = sb2;
		sb2.append(sb1);
	}

	public static void change(String s1, String s2) {
		s1 = s2;
		s2 = s1 + s2;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章