This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question about final! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about final!" Watch "A question about final!" New topic

A question about final!

Ranch Hand

Joined: Sep 14, 2000
Posts: 30
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;
06: Base() { }
07: void test() {
08: System.out.println("Base.test()");
09: }

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

Joined: Sep 29, 2000
Posts: 4
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

Joined: Oct 04, 2000
Posts: 2
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 final int j;
This piece of code will not compile
I agree. Here's the link:
subject: A question about final!
It's not a secret anymore!