Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification in Java basics?

Tags:

java

class test
{
    test() {
        System.out.println("Constructor");
    }

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


public class sample
{
    public static void main(String [] a) {
        test t = new test();        
    }
}

In the above code, why is "Hai" printed before the test() constructor is called?

The test() constructor in the test class is above the "Hai" statement and should be called first, right?

like image 555
Hariharbalaji Avatar asked Dec 12 '09 12:12

Hariharbalaji


3 Answers

Let express with a more clear example:

public class Test {

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

    {
         System.out.println("instance initializer");
    }

    public Test() {
         System.out.println("constructor");
    }

}

and test it as follows:

public class Main {

    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
    }

}

output:

static initializer
instance initializer
constructor
instance initializer
constructor

The static initializers are executed only once during runtime, specifically during loading of the class. The instance initializers are executed during every instantiation before the constructor.

You can have more than one of them and they will be executed in the order as they appear in the coding.

The major benefit of instance initializers is that they are executed regardless of which constructor you use. They applies on each of them so that you don't need to duplicate common initialization over all of them.

The major benefit of static initializers is that they are executed only once during class loading. A well known real world example is the JDBC driver. When you do

 Class.forName("com.example.jdbc.Driver");

which only executes the static initializers, then any (decent) JDBC driver will register itself in the DriverManager as follows

 static {
      DriverManager.registerDriver(new com.example.jdbc.Driver());
 }

this way the DriverManager can find the right JDBC driver during getConnection().

like image 90
BalusC Avatar answered Oct 21 '22 04:10

BalusC


Yes. It's an instance initializer. It's run as soon as the class is instantiated.

like image 7
Bombe Avatar answered Oct 21 '22 05:10

Bombe


In the above code why is that the statement given within the braces ((i.e) "Hai") is Printed before the constructor is executed.

Because this is the expected behavior as described in the section 12.5 Creation of New Class Instances of the Java Language Specification :)

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
  2. If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type.)
  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

See section 8.6 Instance Initializers for more details on... instance initializers.

like image 3
Pascal Thivent Avatar answered Oct 21 '22 04:10

Pascal Thivent