This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why ???" Watch "Why ???" New topic

Why ???

momo france

Joined: Oct 10, 2002
Posts: 2
Hi everybody
can you explain me why the result is that ?(look at the following code plz)....
public class test
static int j;

public static void main(String[] args)
new test();

why the result is not
(you have this last result if you omit the word static from the block)
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Because static blocks are intialized before any other execution. On the statement static int j; j is set to a default value of 0. Next the static block is run:

So whether you create an object of test or not Hello will be printed to stdout and the static j will be incremented resulting in a value of 1. Next main is run:

causing the value of j, which is now 1, to be printed to stdout. You create a test object next but that doesn't do anything but take up some space in memory.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Bill Pugh

Joined: Jul 10, 2003
Posts: 12
Actually, just to further clarify, the static intializer for a class C is executed before any instance of C is created and before any static method of C is invoked. So the static initializer for class test is executed before the static method main(String args[]) in class test is executed.
I agree. Here's the link:
subject: Why ???
It's not a secret anymore!