What are the proper ways to initialize the static variables SIZE and MIN_VALUE ? 01: class Base 02: { 03: static final int SIZE; 04: static float MIN_VALUE; 05: 06: Base() { } 07: void test() { 08: System.out.println("Base.test()"); 09: } 10: 11:}
Select all valid answers.
a) Add the following lines to Base Class static { SIZE = 10; MIN_VALUE = 10.3f; } b) Add the following lines to Base Class { SIZE = 10; MIN_VALUE = 10.3f; } c) Add the following lines to Base Class constructor SIZE = 10; MIN_VALUE = 10.3f; d) Modify lines 03 and 04 as static final int SIZE = 10; static float MIN_VALUE = 10.3f; I think d) is right. but in the meanwhile, I have done the test, it shows a) is also right. but who can tell me why?
jon c
Greenhorn
Joined: Sep 29, 2000
Posts: 4
posted
0
Answer a is correct because, static { SIZE = 10; MIN_VALUE = 10.3f; } is a static variable initializer block. This block gets executed when the class is loaded. ---------------- The following block initializes the instance variables when the instance is created. ( so,u cannot use this block to initialize a static final variable) { SIZE = 10; MIN_VALUE = 10.3f; }
[This message has been edited by jon c (edited September 29, 2000).]
Indian Joe
Greenhorn
Joined: Oct 04, 2000
Posts: 2
posted
0
It is clearly specified that static final variable can be assigned vallues only at 2 places 1) when declared 2) in the static intialization block. How ever it should be remembered that when static initialiazation block is used forward referencing shouldnot be done. This will give a compile time error.. what i mean to say is.. class Test { static final int i; static{ j=10; } static final int j; .... .... } This piece of code will not compile