File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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 Java 8 in Action this week in the Java 8 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: 24168
    
  30

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]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: static doubt
 
Similar Threads
The result of instance variable of inheritance.
Difference between static and not static intializer blocks
Threads
about static and instance initializer blocks with inheritance
% operator