Demonstrate static variables, methods and blocks in Java



The static variable is a class level variable and it is common to all the class objects i.e. a single copy of the static variable is shared among all the class objects.

A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object.

The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {    static int x = 10;    static int y;    static void func(int z) {       System.out.println("x = " + x);       System.out.println("y = " + y);       System.out.println("z = " + z);    }    static {       System.out.println("Running static initialization block.");       y = x + 5;    }    public static void main(String args[]) {       func(8);    } }

Output

Running static initialization block. x = 10 y = 15 z = 8

Now let us understand the above program.

The class Demo contains static variables x and y. The static method func() prints the values of x, y and z. A code snippet which demonstrates this is as follows:

static int x = 10; static int y; static void func(int z) {    System.out.println("x = " + x);    System.out.println("y = " + y);    System.out.println("z = " + z); }

The static initialization block initializes the static variable y. In the main() method, the func() method is called. A code snippet which demonstrates this is as follows:

static {    System.out.println("Running static initialization block.");    y = x + 5; } public static void main(String args[]) {    func(8); }
Updated on: 2019-07-30T22:30:24+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements