×

Java Programs

Java Practice

Java program to explain static block and constructor

Here, we are implementing a Java program to explain the static block and constructor.

//Java program to explain static and constructor block.

import java.util.*;
class Sample {
    static {
        System.out.println("**This is STATIC BLOCK.");
    }

    public Sample() {
        System.out.println("##This is CONSTRUCTOR.");
    }
    public void showMessage() {
        System.out.println("Hello World.");
    }
}

public class StaticAndConstructor {

    public static void main(String s[]) {
        Sample S1 = new Sample();
        Sample S2 = new Sample();
        Sample S3 = new Sample();

        S1.showMessage();
        S2.showMessage();
        S3.showMessage();
    }
}

Output

**This is STATIC BLOCK.
##This is CONSTRUCTOR.
##This is CONSTRUCTOR.
##This is CONSTRUCTOR.
Hello World.
Hello World.
Hello World.

Explanation:

Here "**This is STATIC BLOCK." called once because this message was written into static block, Message "##This is CONSTRUCTOR." called three time because it was written in constructor and when object created constructor called. "Hello World." called three time because it was written in method showMessage() and this method called three time.

Java Static Variable, Class, Method & Block Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.