This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Can anyone explain to me what is the difference between a static and a final variable? Aren't both of them the same? I also encounter such cases wherein they are both use to declare a certain variable like for example: static final int LENGTH = 1000.
Making a variable static doesn't make it constant at all. However if a variable does represent a compile-time constant, it might as well be static. But whether or not a variable represents a constant is completely independant of whether it's marked static. In order to be a compile-time constant, a variable must be final, and it must be a primitive type or String, and it must be initialized at the time it's declared, and using a value which is itself a compile-time constant expression.
A local variable may also be a constant, though of course a local variable cannot ever be static. If a non-local variable is a constant, then there is really no reason not to make it static (since all instances have the same value) however it's not a requirement.
In short, being static has almost nothing to do with being constant, except they do often go together.
"I'm not back." - Bill Harding, Twister
Joined: Feb 07, 2005
Sorry, I didn't mean to imply that being static made it a constant. I was just referring to the combination of the two identifiers makes one copy of a class variable whose value can never be changed as opposed to a final instance variable where there is a seperate copy of that variable for each instance and is constant only for that instance.
Joined: Jan 30, 2000
OK. And I should note that every time I said constant, I meant a compile-time constant, which is different than just being a variable that doesn't change. Mario probably doesn't need to worry about that anyway, and should probably skip my post for now. I just didn't want misleading information to be propagated. Mario, it's probably better to just skip any mention of "constant" until you have a better understanding of static and final, which are really completely different things.
Joined: Mar 09, 2005
Ok. Now it's quite clear to me as to what is the difference between static and final. I just thought that both of them are the same and somewhat are closely related to each other. Anyway, thanks a lot for the reply.