1. 判斷定義為String類型的s1和s2是否相等
String s1 = "ab"; String s2 = "abc"; String s3 = s1 + "c"; System.out.println(s3 == s2); //true System.out.println(s3.equals(s2)); //true
解答:
false //s1是變量,s2與常量"c"相加 true
2. String與StringBuffer傳遞
1 /** 2 * 基本數據類型的值傳遞,不改變其值 3 * 引用數據類型的值傳遞,改變其值 4 */ 5 private static void test4() { 6 String s = "heima"; 7 System.out.println(s); 8 change(s); 9 System.out.println(s); 10 11 System.out.println("------------------"); 12 StringBuffer stringBuffer = new StringBuffer(); 13 stringBuffer.append("heima"); 14 System.out.println(stringBuffer); 15 change(stringBuffer); 16 System.out.println(stringBuffer); 17 } 18 19 /** 20 * 調用該方法時實際參數的sb和形式參數的sb指向的是同一個對象(StringBuffer容器) 21 * 方法內部又在該容器里添加了"itcast",所以方法結束時,局部變量的sb消失,但是 22 * 實際參數的sb所指向的容器的內部的內容已經發生了改變 23 * @param stringBuffer 24 */ 25 private static void change(StringBuffer stringBuffer) { 26 stringBuffer.append("itcast"); 27 } 28 29 /** 30 * 因為str是屬於局部變量,在調用該方法是實際參數s和形式參數str指向的是同一個對象,但是 31 * 在方法內部將str又指向了一個新的字符串對象,而此時s還是指向的原來的字符串對象 32 * 該方法執行完畢,局部變量str消失,方法內部產生的新的字符串對象稱為垃圾,但是s還是指向 33 * 原有的字符串對象,並沒有改變 34 * @param str 35 */ 36 private static void change(String str) { 37 str += "itcast"; 38 }
3. Integer的面試題
1 private static void test5() { 2 Integer i1 = 97; 3 Integer i2 = 97; 4 System.out.println(i1 == i2); 5 System.out.println("-----------------"); 6 7 Integer i3 = 199; 8 Integer i4 = 199; 9 System.out.println(i3 == i4); 10 11 /** 12 * -128到127是byte的取值范圍,如果在這個取值范圍內,自動裝箱就不會新創建對象, 13 * 而是從常量池中獲取,如果超過了byte取值范圍就會再新創建對象 14 * 源碼分析: 15 */ 16 public static Integer valueOf(int i) { 17 if (i >= -128 && i <= 127) 18 return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)]; 19 return new Integer(i); 20 } 21 }
4. 為什么針對安全保密高的信息,char[]比String更好?
因為String是不可變的,就是說它一旦創建,就不能更改了,直到垃圾收集器將它回收走。而字符數組中的元素是可以更改的。這就意味着可以在使用完之后將其更改,而不會保留原始的數據)。
所以使用字符數組的話,安全保密性高的信息(Eg. 密碼之類的)將不會存在與系統中被他人看到。
5. 如何將字符串轉換成時間
1 private static void test6() { 2 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 3 String today = simpleDateFormat.format(new Date()); 4 ParsePosition position = new ParsePosition(0); 5 Date date = simpleDateFormat.parse(today, position); 6 }
6. 如何計算一個字符串某個字符的出現次數?
1 private static void test7() { 2 int n = StringUtils.countMatches("111122233333111", "1"); 3 System.out.println(n); 4 }
7. 如何重復一個字符串
1 private static void test8() { 2 String str = "abcd "; 3 String repeated = StringUtils.repeat(str, 3); 4 System.out.println(repeated); 5 }
