Static variable in java program

Static variable V/S Normal Variable

Java is one programming languages. In this language, java introduces different variables in programs. Like abstract variable, final variable, static variable etc.

In this blog we will understand basic different of static and non-static variables.

 

 

Let’s see example on static and non-static methods in java programs.

class A

{

            static int x = 10;            // Static variables can continue work with all object

            int y = 20;                                 // Every time start with new value

 

            void setA()

            {

                        x++;     // x = 11 , x = 12 , x = 13

                        y++;     // Y = 21 , Y = 21 , Y = 21

            }

            void display()

            {

                        System.out.println(“X = ” + x);

                        System.out.println(“Y = ” + y);

            }

}

class clEx13

{

            public static void main(String args[])

            {

                        A a1 = new A();

                        A a2 = new A();

                        A a3 = new A();

 

                        a1.setA();

                        a1.display();

 

                        a2.setA();

                        a2.display();

 

                        a3.setA();

                        a3.display();

            }

}

 

Output:

X = 11

Y = 21

X = 12

Y = 21

X = 13

Y = 21

 

In this blog example, x is static variable and y is non-static variable. Static variable x is keep storing value of old object’s process. A1,a2 and a3 are object of this class. A2 object follow the value of a1 object. And a3 object follow the value of a2 object.

 

 

Video available on YouTube.


[sbscrbr_form]

If you have query about this blog, you can directly post comment or subscribe on website.


 

Earn Money Online

1032total visits,9visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image