Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final variables 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 "final variables" Watch "final variables" New topic

final variables

Chun Wang
Ranch Hand

Joined: Jan 24, 2001
Posts: 42
Hello .
I have a question about final variables:
It seems to me that if a final MEMBER variable (ie.not local variable) is left blank, it won't compile.(it will compile if you initialize it in an initializer or in every constructor but not later). however if a final LOCAL variable is left blank and as long as it's NOT used anywhere, it will still compile. is this true? please confirm my understanding.
thanks so much for your help.
Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
The code below worked. I remember a reference that the final variable can be declared, and later initalized at a specific spot. I do not recall the exact spot.
import java.*;
public class d {
//final int num; this line produced a compile time error
// since num was not referenced
public void aMethod() {final int finalarg; }
public static void main (String args []) {
nidiya gaspar

Joined: Jan 31, 2001
Posts: 7
I tried using final variables as member variables without initializing. It gives compile time error even if it is not used anywhere in the program.
But local variables can be left unassigned, if it is not used anywhere in the program. It gives no error.
So ur assumption is correct.
All the best
quan zhu

Joined: Dec 14, 2000
Posts: 27
Correct me if I am wrong:
1) final variable must be initialized before it is used, no default value will be assigned (local or instance)
2)final class member must be assigned when it is declared or before the end of the construtor.
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
A final variable doesn't need to be initialized at the time of declaration, but it must be initialized before it is used. These are also known as blank final variables. - This comes from Khalid page123.
Shrini Kulkarni
Ranch Hand

Joined: Jan 12, 2001
Posts: 63
Correct me if I am wrong. All instance variables of class whether final or not, are initialised to default values where as local variables are NOT. what difference it makes for giving default value to a final instance variable if there is no explicit value is assigned ?
class A
final int SomeNumber; // instance variable not local hence
.... // should be given a default value

My question is why final instance variable is treated diffrently
as regard to assignment of default value when there is no expilcit value is assigned in any initialisers or constructors ?

Sun Certified programmer for Java2 platform.<BR>
I agree. Here's the link:
subject: final variables
It's not a secret anymore!