Java program for static block

Static Block

Static block is used to initialize or change the java default static variables. When class is loaded this block gets executed and all static variables initialized.

In a class there may be multiple static block, they will be loaded in the sequence in which they are declared.

Program:

// Java program to demonstrate example of static block.

import java.util.*;

public class StaticBlock {
    //static variables
    static int a;
    static int b;
    static int c;

    //static block1 
    static {
        System.out.println("I'm in static block 1.");
        a = 10;
    }
    //static block2
    static {
        System.out.println("I'm in static block 2.");
        b = 20;
    }
    //static block3 
    static {
        System.out.println("I'm in static block 3.");
        c = 30;
    }
    public static void main(String[] s) {
        System.out.println("Value of a: " + a);
        System.out.println("Value of a: " + b);
        System.out.println("Value of a: " + c);
    }
}

Output:

I'm in static block 1.
I'm in static block 2.
I'm in static block 3.
Value of a: 10
Value of a: 20
Value of a: 30

There are three static blocks in this program and they loaded before executing main() function in sequence in which they are declared.

Java Static Variable, Class, Method & Block Programs »






Comments and Discussions!

Load comments ↻






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