Q:

Java program for static block

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now