wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes compile time constants Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "compile time constants" Watch "compile time constants" New topic
Author

compile time constants

Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
Henry had once written in a post long time back that

Instance variables (that are not compile time constants) get initialized in the order that they appear in the source (from top to bottom, and left to right). And any forward reference to them, will have them at their default values.


what about compile time constants?
in what order do they get initialise?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18523
    
  40


Well, compile time constants are ... constants. The Java compiler should optimize out the variables entirely, and use the constant instead.

Or another way to look at it. Constant variables are initialized first -- before everything else.

Henry


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

Joined: Sep 06, 2009
Posts: 531
Thanks Henry
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
class Forward
{
private int x=y+10;
private int y=5;

private int a=b+4;
private final int b=100;


}

why is there an error in the last one....isnt b initialised before everything else
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18523
    
  40

Ankur kothari wrote:
why is there an error in the last one....isnt b initialised before everything else


Well, what is it about the error message that you don't understand?

Henry
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
since final variables are initialized before all so isn't the statement int a=b+4 actually int a=100+4 ???
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18523
    
  40

Ankur kothari wrote:since final variables are initialized before all so ....


Note: final variables and compile time constants are not the same thing. The statement that final variables are initialized first, is untrue.


Ankur kothari wrote: ... isn't the statement int a=b+4 actually int a=100+4 ???


Probably. After the optimizer gets to it. However, there is nothing in the JLS that allows compile time constants to be exempted from the forward referencing rules... so, this is still illegal according to the spec.

Henry
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
ok understood....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compile time constants
 
Similar Threads
How many String objects are created.
how does this piece of code work? forward referencing?
Doubt about the initialization block order of execution
Static Final Variables Query
compile time constant.