This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static v/s Non-Static Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Static v/s Non-Static" Watch "Static v/s Non-Static" New topic
Author

Static v/s Non-Static

Murtuza Akhtari
Ranch Hand

Joined: Aug 07, 2004
Posts: 108
What is the output of the following code?

A) Test(1)
Test(2)
Test(3)

B) Test(3)
Test(2)
Test(1)

C) Test(2)
Test(1)
Test(3)

D) Test(1)
Test(3)
Test(2)

Answer : D
Explanation : No matter where they are declared, static variables will be initialized before non-static variables

I m still confused about the printing order...In the first call to the constructor why wouldnt Test(2) print before Test(3) even if 2 is initialized later?

[ August 09, 2004: Message edited by: Murtuza Akhtari ]
[ August 09, 2004: Message edited by: Murtuza Akhtari ]

---<br />SCJP 1.4
Aarti Dahiya
Greenhorn

Joined: Aug 07, 2004
Posts: 15
Static variables are declared and initialized when the class gets loaded at runtime. Since they are not tied to a specific instance of a class, their declaration and initialization does not wait for an instance of a class to be created. t1 and t3 are declared and initialized when the class is loaded, so the Test construtor is called twice separately and prints Test1, Test3.
main() is executed at runtime after the class has been loaded. In main() when an instance of class Q12 is created, its instance variable t2 is declared and initialized. The Test construcor is called and prints Test2.


SCJP 1.4 (95%)
Murtuza Akhtari
Ranch Hand

Joined: Aug 07, 2004
Posts: 108
Thanks Aarti !!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Static v/s Non-Static
 
Similar Threads
Some Codes
problem with if clause
Method invoking
Threads
Question on Dan's Mock