• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

abou final variable

 
rameshbabu yarlagadda
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class ExFn{
final int x;
void display(){
x=10;
System.out.println(x);
}
public static void main(String[] args){
ExFn a=new ExFn();
a.display();
}
}

when we are compiling this code it gave an compile error that we can't initialize x value

why can't we assign a value for final variable in a method
why in constructor only.
 
krishnamoorthy kitcha
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

If you used final keyword, we can't redefine, just use the variable,

Not to reassign and other operations.

That is the use of the final keyword.

Rgks
k.krishnamoorthy
 
rameshbabu yarlagadda
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know final variable are not reinitialized, but in the code i was not initialize the x value just i declared the x value, why can't initialize a final variable x in a method
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by rameshbabu yarlagadda:
i know final variable are not reinitialized, but in the code i was not initialize the x value just i declared the x value, why can't initialize a final variable x in a method


Because you can't *initialize* a field in a method, you can only *change* it's value.

What value would the field have before you call the method?

What should happen if you call the method more than once?
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are only two ways to initialize a final field: either directly in the declaration, or in a constructor. Any other way is not allowed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic