*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why ???" Watch "Why ???" New topic
Author

Why ???

momo france
Greenhorn

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;

static
{
System.out.println("Hello");
j++;
}
public static void main(String[] args)
{
System.out.println(j);
new test();
}
}
..................................................
Hello
1

why the result is not
0
Hello
(you have this last result if you omit the word static from the block)
THANKS
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
Greenhorn

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: http://aspose.com/file-tools
 
subject: Why ???