Static Keyword

PREVIOUS

static keyword

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 instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1) static variable

If you 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. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Example of static variable

  1. //Program of static variable  
  2.   
  3. class Student8{  
  4.    int rollno;  
  5.    String name;  
  6.    static String college ="ITS";  
  7.      
  8.    Student8(int r,String n){  
  9.    rollno = r;  
  10.    name = n;  
  11.    }  
  12.  void display (){System.out.println(rollno+" "+name+" "+college);}  
  13.   
  14.  public static void main(String args[]){  
  15.  Student8 s1 = new Student8(111,"Karan");  
  16.  Student8 s2 = new Student8(222,"Aryan");  
  17.    
  18.  s1.display();  
  19.  s2.display();  
  20.  }  
  21. }  

2) static method

If you 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 instance of a class.
  • static method can access static data member and can change the value of it.

Example of static method

  1. //Program of changing the common property of all objects(static field).  
  2.   
  3. class Student9{  
  4.      int rollno;  
  5.      String name;  
  6.      static String college = "ITS";  
  7.        
  8.      static void change(){  
  9.      college = "BBDIT";  
  10.      }  
  11.   
  12.      Student9(int r, String n){  
  13.      rollno = r;  
  14.      name = n;  
  15.      }  
  16.   
  17.      void display (){System.out.println(rollno+" "+name+" "+college);}  
  18.   
  19.     public static void main(String args[]){  
  20.     Student9.change();  
  21.   
  22.     Student9 s1 = new Student9 (111,"Karan");  
  23.     Student9 s2 = new Student9 (222,"Aryan");  
  24.     Student9 s3 = new Student9 (333,"Sonoo");  
  25.   
  26.     s1.display();  
  27.     s2.display();  
  28.     s3.display();  
  29.     }  
  30. }  

 
PREVIOUS

No comments:

Post a Comment