Java OCA OCP Practice Question 2895

Question

Given:

2. public class Main {  
3.   static int x = 1;  
4.   public static void main(String[] args) {  
5.     int x = 2;  
6.     for(int i=0; i< 3; i++) {  
7.       if(i==1) System.out.print(x + " ");  
8.     }  //from w  w w.ja v a2  s . c o  m
9.     go();  
10.      System.out.print(x + " " + i);  
11.   }  
12.   static void go() { int x = 3; }  
13. } 

What is the result?

  • A. 1 2 2
  • B. 2 2 2
  • C. 2 2 3
  • D. 2 3 2
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


E is correct.

Note

When the code reaches line 10, the variable "i" is out of scope.

If "i" was not mentioned on line 10, scoping and shadowing rules would create the output: "2 2".




PreviousNext

Related