下面的代碼有什麼不妥之處?
1. if(username.equals(“wpc”)){}
2. int x = 1;
return x==1?true:false;
回答一問題:如果username初值爲null在編譯的時候會有警告,運行的時候拋出異常
如果username寫在後面即使初值爲null也不會拋異常
回答問題二:代碼冗餘無需還要三木運算符判斷是否爲true或者false,直接返回boolean類型就可以了
也就是說wpc.equals(username)更好;return x= =1,就可以了。
----------------------------------時間分割線-------------------------------------------
1.public static void main(String[] args) {
// TODO 自動生成的方法存根
Thread t = new Thread() {
public void run() {
pong();
}
};
t.start();
System.out.print("ping");
}
static void pong() {
System.out.print("pong");
}
}
會輸出什麼?答案是:pongping和pingpong都有可能。
public static void main(String[] args) {
// TODO 自動生成的方法存根
Thread t = new Thread() {
public void run() {
pong();
}
};
t.run();
System.out.print("ping");
}
static void pong() {
System.out.print("pong");
}
}
會輸出什麼?答案是:pongping。
解析:由於啓動多線程的方法是start()而非run(),所以第二個代碼片段,根本不是多線程,只有一個主線程在運行,調用了重寫的run()而已;第一個代碼段中,主線程和子線程是隨機執行的,誰能搶到CPU的資源,誰就執行。
2.
public void getCustomerInfo() {
try {
// do something that may cause an Exception
} catch (java.io.FileNotFoundException ex) {
System.out.print("FileNotFoundException!");
} catch (java.io.IOException ex) {
System.out.print("IOException!");
} catch (java.lang.Exception ex) {
System.out.print("Exception!");
}
}
A IOException!
BIOException!Exception!
CFileNotFoundException!IOException!
DFileNotFoundException!IOException!Exception!
答案:A
解析:只catch一次,能匹配到就終止,不再拋錯誤。
3.
新建一個流對象,下面哪個選項的代碼是錯誤的?()
A)new BufferedWriter(new FileWriter("a.txt"));
B)new BufferedReader(new FileInputStream("a.dat"));
C)new GZIPOutputStream(new FileOutputStream("a.zip"));
D)new ObjectInputStream(new FileInputStream("a.dat"));
答案:B
JAVA的IO繼承樹
4.
下列哪種異常是檢查型異常,需要在編寫程序時聲明?
-
A.NullPointerException
-
B.ClassCastException
-
C.FileNotFoundException
-
D.IndexOutOfBoundsException
-
答案爲C
綠色部分Exception是非檢查型異常,必須run一下才會發現。其他的在編譯時就會發現。
5.序列化問題。
JAVA種帶有transient和static關鍵字的變量,不會被序列化。static變量和類同級別,序列化針對的是對象。
6.hashmap、arraylist原理以及擴容問題,另開一個博文說明。
7.JAVA構造函數加載順序。牽扯到JAVA加載順序,另開一個博文說明。
8.static變量會被初始化爲0,字符串是null。局部變量不初始化編譯不通過。
9.接口和抽象類的區別與聯繫,以及其中的變量、函數的類型,另開博文說明。