Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sample Code Problem

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can someone please tell me whats causing the problem here?



I feel it's because, when we declare a variable as final, we HAVE to give the variable a value and it does not get a default value as variables which are not initialized(The not final variables). Is that correct?

Thanks.

[edit]Add code tags. CR[/edit]
[ September 07, 2008: Message edited by: Campbell Ritchie ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed, isn't this what the error message tells you?
 
Sachin Joshi
Ranch Hand
Posts: 83
Java Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static final field has to be initialized when its declared, can you think of any other place where you can initialize it?

I think it makes perfect sense to stop it during compile time itself.

If its a non static (instance) final field then you can initialize it in the constructor as well.
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your answers guys. Yes, static final variables can also be initialized in static initializer blocks.

Thanks.
[ September 06, 2008: Message edited by: Arjun Reddy ]
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well you could but it would make writing the compiler a lot harder. It would have to check if there is a static initializer block somewhere that initializes the field, and more importantly - if the field is not used before that, either in the same block or a previous static initializer block.

If you don't know the direct value when compiling, it is possible to use the results of a static method:

That one is taken directly from java.io.File. System.getProperty is also an often used source for static final fields.
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic