Java OCA OCP Practice Question 965

Question

How many compiler errors are in the following code?

1: public class MainSwing { 
2:   private static final String leftMain; 
3:   private static final String rightMain; 
4:   private static final String bench; 
5:   private static final String name = "name"; 
6:   static { //from  w ww.ja v  a  2s . c om
7:     leftMain = "left"; 
8:     rightMain = "right"; 
9:   } 
10:   static { 
11:     name = "name"; 
12:     rightMain = "right"; 
13:   } 
14:   public static void main(String[] args) { 
15:     bench = "bench"; 
16:   } 
17: } 
  • A. 0
  • B. 1
  • C. 2
  • D. 3
  • E. 4
  • F. 5


E.

Note

static final variables must be set exactly once, and it must be in the declaration line or in a static initialization block.

Line 4 doesn't compile because bench is not set in either of these locations.

Line 15 doesn't compile because final variables are not allowed to be set after that point.

Line 11 doesn't compile because name is set twice: once in the declaration and again in the static block.

Line 12 doesn't compile because rightMain is set twice as well.

Both are in static initialization blocks.




PreviousNext

Related