• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cofused about output of program..?

 
Naveen Megharaj
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everybody, the following program produces the output:
Test(1)
Test(3)
Test(2)

Can anybody explain HOW and WHY?
Program is as shown below:


class Test
{
Test(int i)
{
System.out.println("Test(" +i +")");
}
}

public class Q12
{
static Test t1 = new Test(1);
Test t2 = new Test(2);

static Test t3 = new Test(3);

public static void main(String[] args)
{
Q12 Q = new Q12();
}
}
 
Eric Bruno
author
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is correct, and happens because static intializers execute when the VM starts. Therefore, your static references t1 and t3 get created first, and then t2 (non-static) gets created once your application begins executing. Since static instance t1 is declared before t3, it gets created in that order.
 
Naveen Megharaj
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But Sir, static blocks have a syntax of:

static {

}

But in my program , they are not static blocks, They are just static reference variables. As far as i know only static blocks gets executed before the main() method is started. So i m still confused about the output............!!!
 
Eric Bruno
author
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although t1 and t3 are declared as static fields, they are still statically initialized, and my explanation still applies.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eric is right. Not only static initializer blocks, but also initializations of static fields are run when the class is loaded.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic