Sunday, August 15, 2010

Variable Scope: Banana.java

Courtesy of Sun Web Learning Center

 1. class Banana {
 2.   int x = 1;
 3.   public static void main(String [] args) {
 4.     int x = 2;
 5.     Banana b = new Banana();
 6.     b.go();   
 7.   }
 8.   { x += x; }
 9.   void go() {
10.     ++x;
11.     System.out.println(x);
12.   }
13. }


What is the result?


A     1
B     2
C     3
D     5
E     Compilation fails.

C is correct. The variable x on line 2 is not the same x as on line 4. The initialization block runs after the new Banana object is created.

No comments:

Post a Comment