1

Code:

class VI{
    {
        System.out.println("Non static block called");
    }
    VI()
    { 
        System.out.println("Constructor block called");
    }
    public static void main(String a[])
    {
        VI v=new VI();
    }
}

The code snippet comprises class again it comprised of non static block along with constructor.

So, when obejct of class is created the non static block will be called and after that constructor is called.

So, can we say non static block as constructor of class?

Terminal commands:

vivek@ubuntu:~/Prime_project/python-SLR-parser$ javac VI.java 
vivek@ubuntu:~/Prime_project/python-SLR-parser$ java VI
Non static block called
Constructor block called
vivek@ubuntu:~/Prime_project/python-SLR-parser$ 
Community
  • 1
  • 1
vivek narsale
  • 360
  • 4
  • 10
  • I don't see any static block in your code. You have an [_instance initializer block_](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.6), which executes when an instance is created. it is not `static`. – Ted Hopp Sep 24 '15 at 07:29
  • There are some differences. Hope this will help : http://stackoverflow.com/questions/1355810/how-is-an-instance-initializer-different-from-a-constructor – Rahman Sep 24 '15 at 07:30
  • No, that's not the right way to put it. You can't construct a class by just calling non-static block, but constructor only i.e `new`. Although non-static block would run before a constructor. Please read about the order of initialization [here](http://stackoverflow.com/questions/2007666/in-what-order-do-static-initializer-blocks-in-java-run) – bsingh Sep 24 '15 at 07:35

1 Answers1

4

No, an initializer block is not a constructor.

However, the code inside it is copied into every constructor according to the Java Tutorials:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Keppil
  • 45,603
  • 8
  • 97
  • 119
  • I know that's what the tutorial says, but that's not exactly the behavior defined in the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5) (see step 4 in the linked section 12.5). (Although perhaps it's how Oracle's Java compiler implements the specified behavior.) This answer is essentially correct, though, so +1. – Ted Hopp Sep 24 '15 at 07:34