常見物件_StringBuffer的兩個小面試題、String和StringBuffer分別作為引數傳遞
阿新 • • 發佈:2019-02-20
package cn.itcast_08; /* * 面試題 * 1:String,StringBuffer,StringBuilder的區別? * A:String是內容不可變的,而StringBuffer,STringBuilder內容可變的。 * B:StringBuffer是同步的,資料安全,效率低。 * C:StringBuilder是不同步的,資料不安全,效率高。 * 2:StringBuffer和陣列的區別? * 二者可以看出是一個容器,裝其它的資料。 * 但是呢,StringBuffer資料最終是一個字串資料。//sb.append(true).append(123)。 * 而陣列可以放置多種資料,但必須是同一種資料型別的。//int[] arr = {1,2,3}資料型別必須相同 * 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(s1 + "---" + s2);//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; } }