剛在論壇上看到http://www.iteye.com/topic/681784的幾道面試,測試了一下,收穫不小,特此mark
public class test1 {
public static boolean get(){
try{
//System.out.println("Get false");
return false;
}
// catch(Exception e){
// e.printStackTrace();
// System.out.println("Ex true");
// return true;
// }
finally{
return true;
}
}
public static void main(String... strings){
System.out.println(get());
}
}
結果:true
說明在finally中,無論是否return都會執行,當用System.exit()是纔會退出。and return只是終止一個模塊的運行
2. public static void main(String[] args) {
String classPath1 = "java.lang.string";
System.out.println(classPath1.replaceAll(".", "A"));
//System.out.println(classPath1.replaceAll("\\.", "A"));
}
結果:全部替換,以爲“.”在JDK中解釋爲
預定義字符類 | |
---|---|
. | 任何字符(與行結束符 可能匹配也可能不匹配) |
\d | 數字:[0-9] |
\D | 非數字: [^0-9] |
\s | 空白字符:[ \t\n\x0B\f\r] |
\S | 非空白字符:[^\s] |
\w | 單詞字符:[a-zA-Z_0-9] |
\W | 非單詞字符:[^\w] |
3.public static void main(String ...strings){
StringBuilder sb=new StringBuilder();
switch(1){
case 1:sb.append("Hello a");
case 2:sb.append("b");
case 3:sb.append("c");
default:sb.append("d");
}
System.out.println(sb.toString());
}
這個問題不難,但是爲什麼要用StringBuilder呢?我平常都用StringBuffer,還是jdk中間分曉。
一個可變的字符序列。此類提供一個與 StringBuffer
兼容的 API,但不保證同步。該類被設計用作
StringBuffer
的一個簡易替換,用在字符串緩衝區被單個線程使用的時候(這種情況很普遍)。如果可能,建議優先採用該類,因爲在大多數實現中,它比
StringBuffer
要快。
將 StringBuilder
的實例用於多個線程是不安全的。如果需要這樣的同步,則建議使用StringBuffer線程安全的可變字符
序列
4.
public static void main(String[] args) {
int j = 0;
// System.out.println(j++);
for (int i = 0; i < 100; i++)
j = j++;
System.out.println(j);
}
結果:0,這個沒什麼可講的,就是不要被自己的知識迷惑
6. public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(1);
} finally {
System.out.println("Goodbye world");
}
}
結果:Hello world,可以與1進行比較
6 public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(1999, 12, 31); // Year, Month, Day
System.out.print(cal.get(Calendar.YEAR) + " ");
Date d = cal.getTime();
System.out.println(d.getDay());
}
結果:2000 1 總體感覺沒意思