my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final member variable 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 member variable" Watch "final member variable" New topic
Author

final member variable

David Cuesta
Greenhorn

Joined: Nov 07, 2001
Posts: 25
public class myClass{
static final String myString;
public static void main(String e[]){
System.out.println(myString);
}
}
Why does not compile?
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Originally posted by David Cuesta:
public class myClass{
static final String myString;
public static void main(String e[]){
System.out.println(myString);
}
}
Why does not compile?

David..
You have the double trouble situation
Its static and final..
So you must initialize the string before you access it
If it is just a member final variable rather than static
then you can initialize it inside its constructor
HIH
Ragu
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
final variable (i.e. constants) are not implicitely initialized during class initialization. Final variables have to be initialized either at declaration time or in each constructor of your class.
From JLS 16

Each local variable (�14.4) and every blank final (�4.5.4) field (�8.3.1.2) must have a definitely assigned value when any access of its value occurs. A Java compiler
must carry out a specific conservative flow analysis to make sure that, for every access of a local variable or blank final field f, f is definitely assigned before the
access; otherwise a compile-time error must occur.
Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. A Java compiler must carry out
a specific conservative flow analysis to make sure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment;
otherwise a compile-time error must occur.

HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
 
subject: final member variable