This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Looking for explanation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Looking for explanation" Watch "Looking for explanation" New topic
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: 18509
    
  40


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: 19651
    
  18

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 - OCEEJBD 6
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: 19651
    
  18

First usage. You can verify this using the following example:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Looking for explanation
 
Similar Threads
Order of Static initialization Block,Instance initialization Block and Constructor....
Static variable initialization
constructor and main whichone will execute first..
Main Method Doubt
compilation fails why?