File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about final!" Watch "A question about final!" New topic
Author

A question about final!

laura_zpf
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;
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
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
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.
 
subject: A question about final!
 
Similar Threads
Static variable.
final variable
Conditional Operator with different return types
Assignment Problem
Why a & b are same ?