Question 12
12. Given:
13. public class Pass {
14. public static void main(String [] args) {
15. int x = 5;
16. Pass p = new Pass();
17. p.doStuff(x);
18. System.out.print(“main x = ”+ x)
19. }
20.
21. void doStuff(int x) {
22. System.out.print(” doStuff x = ”+ x++)
23. }
24. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuffx = 6 main x = 6
D. doStuffx = 5 main x = 5
E. doStuffx = 5 main x = 6
F. doStuffx = 6 main x = 5
Answer: D应该是在执行了doStuff后X++由5变6啦,再都X是全局变量,所以doStuff执行完后应该也就是X++已经完成并且新值可以被调用啊??怎么不是6呢?我自己先的答案应该是E。
请问答案如何解释呢?谢谢
12. Given:
13. public class Pass {
14. public static void main(String [] args) {
15. int x = 5;
16. Pass p = new Pass();
17. p.doStuff(x);
18. System.out.print(“main x = ”+ x)
19. }
20.
21. void doStuff(int x) {
22. System.out.print(” doStuff x = ”+ x++)
23. }
24. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuffx = 6 main x = 6
D. doStuffx = 5 main x = 5
E. doStuffx = 5 main x = 6
F. doStuffx = 6 main x = 5
Answer: D应该是在执行了doStuff后X++由5变6啦,再都X是全局变量,所以doStuff执行完后应该也就是X++已经完成并且新值可以被调用啊??怎么不是6呢?我自己先的答案应该是E。
请问答案如何解释呢?谢谢
22. System.out.print(” doStuff x = ”+ x++) //这里的x++只是对doStuff中的传入参数进行修改,与外面定义的x无关
23. }
1) 在doStuff()里,会先“+”(这里表示字符串相连)x, 然后(x + 1), 所以x = 5;
2) 因为x是int基本类型,而JAVA是值传递,所以(x+1)中的1只是传进来的x的一个拷贝。换句话说,全局变量x在doStuff()中被屏蔽了,所以全局变量的x还是5.
import java.util.Arrays;
public class ObjectArray {
public static void main(String arg[]){
int x = 5;
ObjectArray oa = new ObjectArray();
oa.doSuffer(x);
System.out.println("mainx = " + x);
}
private void doSuffer(int x){
System.out.println("doStuff x = " + x++);
System.out.println("x = " + x);
}
}
就看得更明明白白了。