• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static doubt

 
sharma anurag
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic