aspose file tools*
The moose likes Beginning Java and the fly likes static doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static doubt" Watch "static doubt" New topic
Author

static doubt

sharma anurag
Greenhorn

Joined: Aug 29, 2007
Posts: 16
class Question10
{
Question10()
{
System.out.println("1");
}

{
System.out.println("2");
}

static
{
System.out.println("3");
}

public static void main(String[] args)
{
new Question10();
}
}
Ans: is 3,2,1.
Hi all,
as of my knowledge static block will execute first in the above program but why is it printing the statement about the static block before the constructor block?
According to me it should print 3,1,2. Please help me
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

There are three print statements in the above. In order, they appear in (1) the constructor, (2) an initializer block, and (3) a static initializer block. Static initializer blocks are executed right after a class is loaded, so that's why "3" is printed first. The other initializer blocks are inserted into each constructor, right after the "super" call and before the statements in the body of the constructor; that's why "2" is printed next, as it's the first thing that happens in the constructor.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static doubt