This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about final!

 
laura_zpf
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic