Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why ???

 
momo france
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bill Pugh
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic