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. }
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5
Answer: D
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. }
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5
Answer: D
Explanation:
This is a good example of how parameters are passed into the methods.Remember that always parameters are passed copy by value i.e changes in any value of the parameter in called method doesn't have affect in parameter in calling method.
Called method: doStuff()
Calling method : main method ( p.doStuff calls doStuff() method).
In the above example x is initialized with 5 and x is passed by copy by value to doStuff method .Here in the doStuff method we are post incrementing the value of x.But always SOP will print the value of x first then when ;(semicolon) is encountered the x gets incremented to 6 from 5.So doStuff x = 5 is printed.
Now the x in the main method will be 5 and not 6 because both methods x value have different memory locations and resources. Option D.
0 comments:
Post a Comment