面試例題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
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);
public class Test {
public static void main(String[] args){
boolean b = true?false:true == true?false:true;
System.out.println(b);
}
}
運算符優先級:
1級 —— . ()
2級 —— ++ --
3級 —— new
4級 —— * / %
5級 —— + -
6級 —— >> <<
7級 —— > < >= <=
8級 —— == !=
9級 —— &
10級 —— ^
11級 —— !
12級 —— &&
13級 —— ||
14級 —— ?:
15級 —— = += -= *= /= %= ^=
16級 —— &= <<= >>=