Class and Static Variables in Java

JavaServer Side ProgrammingProgramming

Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword ‘static’.

Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.

Example

 Live Demo

public class Demo{
   static int my_count=2;
   public void increment(){
      my_count++;
   }
   public static void main(String args[]){
      Demo obj_1=new Demo();
      Demo obj_2=new Demo();
      obj_1.increment();
      obj_2.increment();
      System.out.println("The count of first object is "+obj_1.my_count);
      System.out.println("The count of second object is "+obj_2.my_count);
   }
}

Output

The count of first object is 4
The count of second object is 4

A class named Demo defines a static variable, and a function named ‘increment’ that increments the value of the static variable. The main function creates two instances of the class, and the increment function is called on both the object. The count is printed on the screen. It shows that static variable is shared between objects.

raja
Published on 17-Aug-2020 09:32:10
Advertisements