wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes How to identify compile time constants Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to identify compile time constants" Watch "How to identify compile time constants" New topic
Author

How to identify compile time constants

Dash Abhisek
Ranch Hand

Joined: Jul 20, 2008
Posts: 63
Hi All,

I found
final int a=10;//line 1 is compile time constant
but,
final int b;//line 1
b=5; // line 2
here b is not a compile time constant
why? please explain

Thanks
Abhishek
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18848
    
  40

why? please explain


There is nothing to explain for the left hand side of the assignment, the compiler requires that the declaration be final, be either a primitive type or a string, and be initialized during the declaration.

For the right hand side -- the expression that will be assigned -- it's a bit more complex. The compiler requires that it be assigned a constant expression. If the RHS is not a constant expression, then the declared variable is not a compile time constant.

See section 15.28, for the definition of constant expression:

http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Dash Abhisek
Ranch Hand

Joined: Jul 20, 2008
Posts: 63
Thanks
 
 
subject: How to identify compile time constants