Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Looking for explanation

 
Luke Kamble
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the topics like static and instance initializes.
 
Henry Wong
author
Marshal
Pie
Posts: 20904
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);".
 
Luke Kamble
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First usage. You can verify this using the following example:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic