2009年2月5日 星期四

第22題

Given:
1. class Pass{
2. public static void main(String[] args){
3. int x= 5;
4. Pass p = new Pass();
5. p.doStuff(x);
6. System.out.print(" main x = " + x);
7. }
8. void doStuff(int x){
9. System.out.println(" doStuff x = " + x++);
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6main x = 6
D. doStuff x = 5main x = 5
E. doStuff x = 5main x = 6
F. doStuff x = 6main x = 5


-----------------------------------------------------------------------------------------------
答案:D
參考:6-2 Java方法
說明:
這題主要考傳值的觀念,
3. int x= 5; //給預設值
...
5. p.doStuff(x);//呼叫 doStuff
...
8. void doStuff(int x){ //將值傳入
9. System.out.println(" doStuff x = " + x++); //先將x print出來後再做+1的動作
(doStuff x = 5)
//第9行執行過後變數x的值不會改變
...
繼續執行
6. System.out.print(" main x = " + x);
(main x = 5)

沒有留言:

張貼留言