Java Program using a static variable


In this program, You will learn how to implement static variables in java.


static int x = 40;

Example: How to implement static variables in java.

class Main {

    int x = 10;
    static int y = 10;

    void change() {
        x++;
        y++;
    }

    void display() {
        System.out.println("x value is:" + x);
        System.out.println("y value is:" + y);
    }

    public static void main(String args[]) {
        Main t1 = new Main();
        t1.change();
        t1.display();

        Main t2 = new Main();
        t2.change();
        t2.display();
    }
}

Output:

x value is:11
y value is:11
x value is:11
y value is:12