• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Jeanne Boyarsky
Saloon Keepers:
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Piet Souris
Bartenders:

A question about final!

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
please buy this thing and then I get a fat cut of the action:
The Low Tech Laboratory Movie Kickstarter is LIVE NOW!
https://www.kickstarter.com/projects/paulwheaton/low-tech
reply
    Bookmark Topic Watch Topic
  • New Topic