Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • The Initializer Block in Java.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 182
    Comment on it

    The Initializer Block in Java

    The initializer block in Java contains code which is executed whenever an instance of class is created therefore this block contains common part for various constructor of a class. The order in which constructor and initializer block are defined does not matter because initializer block is executed whenever constructor is called and is always executed before constructor.


    Program to demonstrate initializer block in Java:-

    import java.io.*;
    public class Demo
    {
        // Initializer block starts..
        {
            // This code is executed before every constructor.
            System.out.println("Common part of constructors invoked !!");
        }
        // Initializer block ends
     
        public Demo()
        {
            System.out.println("Default Constructor invoked");
        }
        public Demo(int x)
        {
            System.out.println("Parametrized constructor invoked");
        }
        public static void main(String arr[])
        {
            Demo obj1, obj2;
            obj1 = new Demo();
            obj2 = new Demo(0);
        }
    }

    Output:

    Common part of constructors invoked!!
    Default Constructor invoked
    Common part of constructors invoked!!
    Parametrized constructor invoked 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: