aspose file tools*
The moose likes Beginning Java and the fly likes abou final variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "abou final variable" Watch "abou final variable" New topic
Author

abou final variable

rameshbabu yarlagadda
Greenhorn

Joined: Jul 15, 2007
Posts: 10
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

Joined: Feb 04, 2006
Posts: 96
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

Joined: Jul 15, 2007
Posts: 10
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

Joined: Jul 11, 2001
Posts: 14112
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?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: abou final variable
 
Similar Threads
final with static
Final keyword???
changing a final variable
final variable related problem.
uninitialized final variable!