• Post Reply Bookmark Topic Watch Topic
  • New Topic

final variable assignment  RSS feed

 
sujesh Katri
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some one please tell me how can i take run time value for static final variable...my lecturer said first time assignment is possible for declared final variable but in my case it shows compile time error..I'm placing my program below with error message
Sample.java:11: cannot assign a value to final variable cname.
cname=args[0];
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sujesh Katri wrote:Some one please tell me how can i take run time value for static final variable...my lecturer said first time assignment is possible for declared final variable but in my case it shows compile time error..I'm placing my program below with error message
Sample.java:11: cannot assign a value to final variable cname.
cname=args[0];


A final static variable can only be assigned once -- during initialization of the variable or via a static initializer. Assignments from a static method isn't allowed, as methods can be called more than once.

Henry
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can writeBut you cannot initialise a final static field in a constructor (that would only work if you had one instance) nor in a method (you can even call the main method several times: as here).

Avoid using multiple initialiser blocks because you can get confused about the order they are executed in.
 
Pallavi Sadit
Ranch Hand
Posts: 50
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sujesh,
For taking runtime value for a final static variable, here is a suggestion:




contents of file ./config/SampleProperty.properties
MYNAME="PALLAVI"

You can change the value of MYNAME each time and run.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!