| Author |
Looking for explanation
|
Luke Kamble
Greenhorn
Joined: Feb 25, 2010
Posts: 7
|
|
Hi, can someone explain me please why this
prints 5. But if I ommit final(like: private static int a = 5;) it prints 0;
Then if I chacge my singleton pattern to this
works fine with or without final near a = 5.(it prints 5)
|
 |
Manish Singh
Ranch Hand
Joined: Jan 26, 2007
Posts: 160
|
|
Read the topics like static and instance initializes.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
Static variables are initialized in the order that they are encountered in the source. So, if you try to use a static variable to initialize another static variable, and that variable is later in source, then you will get the default value.
Final variables that are initialized during declaration, to a compile time constant, are themselves, compile time constants. And since the compiler knows their value are compile time, it is always correct.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
The order is important. If you omit final in the first example, the instance is created before a is given its value of 5. That's why it prints 0 - before the main method is even executed. By making the field final you're turning it into a compile time constant, and compile time constants get substituted by the compiler. In the compiled code with the final keyword in place, field "a" no longer exists. Instead line 8 says "System.out.println(5);".
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Luke Kamble
Greenhorn
Joined: Feb 25, 2010
Posts: 7
|
|
Thank you guys, now I get it.
Just another question, class files are loaded on first useage or when the vm is started?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
First usage. You can verify this using the following example:
|
 |
 |
|
|
subject: Looking for explanation
|
|
|