The moose likes Beginning Java and the fly likes Sample Code Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sample Code Problem" Watch "Sample Code Problem" New topic

Sample Code Problem

Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629

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?


[edit]Add code tags. CR[/edit]
[ September 07, 2008: Message edited by: Campbell Ritchie ]

Be Humble... Be Nice.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Indeed, isn't this what the error message tells you?

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Sachin Joshi
Ranch Hand

Joined: Aug 06, 2008
Posts: 83

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.

Web Development Tips and Tutorials - By Sachin
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Thanks for your answers guys. Yes, static final variables can also be initialized in static initializer blocks.

[ September 06, 2008: Message edited by: Arjun Reddy ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

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 System.getProperty is also an often used source for static final fields.

How To Ask Questions How To Answer Questions
Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
Thanks Rob.
I agree. Here's the link:
subject: Sample Code Problem
It's not a secret anymore!