Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static and final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static and final" Watch "static and final" New topic
Author

static and final

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi,got it from http://www.go4java.20m.com/mock1.htm

public class finex
{
final static int fi=0;
final int fn;
static
{
fi=6;
}
{
fn=8;
}

}

why can't we assign value for final static variable fi in initializer block and also in constructor?
but this is possible with static variable fi.

Please explain me....

Thanks
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

why can't we assign value for final static variable fi in initializer block and also in constructor?
but this is possible with static variable fi.


You cannot assign value to a final static constant inside instance initializer block or constructor as you can use static fields even without making an instance of the class. So the final constant must be initialized with declaration or in a static initializer block.

eg



This is why final constants must be assigned a value in their declaration or static initializer blocks as they run when the class is loaded...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi Ankit,
but i can initialize final variable in initializer block and not in constructor.how about this?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

You can initialize final non-static constants in initializers as well as constructors but not both...
Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
Originally posted by Preetha Arun:
Hi Ankit,
but i can initialize final variable in initializer block and not in constructor.how about this?


you cant assign the final variable in init block. because it will be called everytime new object is created.


<a href="http://technologiquepanorama.wordpress.com" target="_blank" rel="nofollow">My Techie Blog</a><br /><a href="http://www.java-questions.com" target="_blank" rel="nofollow">Java Questions</a>
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488

you cant assign the final variable in init block. because it will be called everytime new object is created.


You CAN assign a final variable in an initialization block because each new object you create will have it's own instance of the variable, unless it's static.


SCJA
~Currently preparing for SCJP6
 
GeeCON Prague 2014
 
subject: static and final