Static Variable In Java

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than object  of the class.

 

If we declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. compnay name for different employees,school  name of students etc.

The static variable gets memory only once in class  at the time of class creation.

 

Understanding problem without static variable

 

class Student

{

     int rollno;

     String name;

     String school=”R.S.Model.Se.Sec”;

}

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

 

2) static method

 

If we apply static keyword with any method, it is known as static method

 

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an object of a class.

static method can access static data member and can change the value of it.

Example of static method

 

//Program of changing the common property of all objects  

  

class Student

{  

     int rollno;  

     String name;  

     static String school = “R.S.Model.Se.Sec.School”;  

       

     static void change()

    {  

                   school = “BCM”;  

     }  

  

     Student(int r, String n)

{  

              rollno = r;  

              name = n;  

     }  

  

     void display ()

{

         System.out.println(rollno+” “+name+” “+school);}  

  

    public static void main(String args[]){  

    Student.change();  

  

    Student s1 = new Student (1,”Navjot”);  

    Student s2 = new Student (2,”Savi”);  

    Student s3 = new Student (3,”Arun”);  

  

    s1.display();  

    s2.display();  

    s3.display();  

    }  

}  

 

Restrictions for static method

 

There are two main restrictions for the static method. They are:

  1. The static method can not use non static data member or call non-static method directly.
  2. this and super cannot be used in static variable and static method.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s