• The variable declared by the keyword static is known as static variable.
  • We know that once a class is declared, we can declare any no. of objects belonging to that class. When all objects want to access a particular variable, then we can declare that variable as static, that means static variable can be used to refer the common property of all objects.
  • The static variable gets memory only once in class area at the time of class loading.
  • It makes your program memory efficient, that means it saves memory.

Suppose there are 1000 students in SILAN Engineering College, now all instance data members will get memory each time when object is created. All student have its unique regdno and name so instance data member is good. Here, the property cname(college name) refers to the common property of all objects. If we make it static, this field will get memory only once.




Example;
package java8s;

class Student
{
      int regdno;
      String name;
      static String cname="SILAN";
     
      Student(int regdno, String name)
      {
            this.regdno=regdno;
            this.name=name;
      }
     
      void show()
      {
            System.out.println(regdno+""+name);
            System.out.println(cname);
      }
}

public class StaticExample1 {

      public static void main(String[] args) {
           
            Student s1=new Student(101,"Sidhant");
            Student s2=new Student(102,"Sonali");
            s1.show();
            s2.show();

      }

}

Output


static variable

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment