This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final with static 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 "final with static" Watch "final with static" New topic
Author

final with static

Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100
This code works fine


But this gives an error
cannot assign a value to final variable x


Can't get the reason why marking it static gives this error regarding final variable.
Sundar Murthi
Ranch Hand

Joined: Mar 05, 2004
Posts: 209
Hi Angela

Non-Static(instance) variables are initialized at the time of object creation.so at first one u r not getting error


But in static members, these are initialized at Class loading time itself
So in "static final int x;" x value must known to the compiler at the time of compilation it self.

i hope it will help u
Sanyev Babu
Ranch Hand

Joined: Dec 18, 2003
Posts: 132
In the second case variable x is a class variable. It should be initialized at the time of definition. We can initialize a final instance variable inside the constructor but not class variable. So you will get a compile time error if you try to initialize a final class variable inside a constructor.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Here's a case where a final static member is initialized at class loading time with a value not known at compile time:



Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Originally posted by Sundar Murthi:
Hi Angela

Non-Static(instance) variables are initialized at the time of object creation.so at first one u r not getting error


But in static members, these are initialized at Class loading time itself
So in "static final int x;" x value must known to the compiler at the time of compilation it self.

i hope it will help u


Going along with Barry's example, the value of static variable is still assigned prior to the class instantiation (it is determined when the class loads since all static block initializers are executed at the time the class loads). Thus, it does not matter that the actual value is known at compile time for the static variable, just that it is assigned when the class loads and before object instantiation (when you class constructor method executes).
 
 
subject: final with static
 
Similar Threads
Swtich Statement
local inner class
Final keyword???
Constuctor problem
Why is this thread closed?