JAVA面試易錯題目總結(一)

面試例題1.下面程序的輸出結果是多少?

public class Test {
	static {
		int x = 5;
	}
	static int x, y;
	public static void main(String[] args){
		x--;
		myMethod();
		System.out.println(x + y++ + x);
	}
	public static void myMethod(){
		y = x++ + ++x;
	}
}
解析:

public class Test {
	static {
		int x = 5;
	}//在第一次載入JVM時運行,但因爲是局部變量,x=5不影響後面的值
	static int x, y;//初始化時x=0,y=0;
	public static void main(String[] args){
		x--;//步驟1.此時x=-1
		myMethod();//步驟3.調用myMethod()函數之後y=0,x=1;
		System.out.println(x + y++ + x);//運行x+(y++)+x=1+0+1=2
	}
	public static void myMethod(){
		y = x++ + ++x;//步驟2.運行y=(x++) + (++x)後y=0,x=1
	}
}

答案:2


面試例題2.下列程序的輸出結果是()

public class Test {
	
	public static void main(String[] args){
		int j = 0;
		for (int i = 0; i < 100; i++){
			j = j++; 
		}
		System.out.println(j);
	}
}
解析:

因爲java用了中間緩存變量的機制,所以,j=j++可換成如下寫法:

temp=j;
j=j+1;
j=temp;

面試例題3.Which  of the following will compile correctly?

A.Short myshort = 99S;                       C.float z = 1.0;

B.int t = "abc".length();                         D.char c = 17c;

解析:

A.要執行自動裝箱,直接寫99就可以;

B.將1.0改爲1.0f就行了,因爲系統默認的浮點數是double型;

C.java中length是屬性,用來求數組長度。length()是方法,用來求字符串長度;

D.直接用char c=17;就好了;



面試例題4.下面代碼的輸出結果是()。

    int i=012;
	int j=034;
	int k=(int)056L;
	int l=078;
	System.out.println(i);
	System.out.println(j);
	System.out.println(k);
A.輸出12,34,56                             C.int k=(int)056L;行編譯錯誤
B.輸出10,28,46                             D.int l=078;行編譯錯誤
解析:int l=078;行編譯錯誤,因爲078是八進制,只能選擇0~7的數字,不應該有8.
答案:D


面試例題5.下列程序的輸出結果是()
public class Test {
	
	public static void main(String[] args){
		boolean b = true?false:true == true?false:true;
		System.out.println(b);

	}
}
解析:三目運算符是右結合性的,所以應該理解爲:
boolean b=true?false:((true==true)?false:true);

運算符優先級:
		1級    —— . ()
		2級    —— ++ --
		3級    —— new
		4級    —— * / %
		5級    —— + -
		6級    —— >> << 
		7級    —— > < >= <=
		8級    —— == !=
		9級    —— &
		10級  —— ^
		11級  —— !
		12級  —— &&
		13級  —— ||
		14級  —— ?:
		15級  —— = += -= *= /= %= ^=
		16級  —— &=  <<= >>=

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