Saturday, August 28, 2010

Instance variable x cannot be referenced from static method main

Courtesy of Sun Web Learning Center


 Given:

 4. public class Utility {
 5.   public static void main(String[] args) {
 6.     System.out.print(x + " ");
 7.     new Utility().go(x);
 8.     System.out.println(x);
 9.   }
10.   private void go(int x) {
11.     x += 5;
12.   }
13.   int x = 7;
14. }

What is the result?


A 7 5
B 7 7
C 7 12
D Compilation fails
E An exception is thrown at runtime

D is correct. Instance variable x cannot be referenced from static method main. If x had been static, this would have been a case of variable shadowing.

No comments:

Post a Comment