Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final member variable

 
David Cuesta
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic