File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes cofused about output of program..? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "cofused about output of program..?" Watch "cofused about output of program..?" New topic
Author

cofused about output of program..?

Naveen Megharaj
Ranch Hand

Joined: Feb 13, 2009
Posts: 39
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

Joined: Jun 15, 2009
Posts: 60
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

Joined: Feb 13, 2009
Posts: 39
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

Joined: Jun 15, 2009
Posts: 60
Although t1 and t3 are declared as static fields, they are still statically initialized, and my explanation still applies.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

Eric is right. Not only static initializer blocks, but also initializations of static fields are run when the class is loaded.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: cofused about output of program..?