Tuesday, 4 August 2015

Static keyword in java


Java Static keyword

For memory management in java used the static keyword.
We can use this keyword with variable,method,blocks and nested class.



In Java Variables can be declared with the “static” keyword.
 

Example: static int x = 0;  
  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variable.
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
Variables which are declared with a static keyword inside a class (outside any method) are known as Class variable / Static variable. They are known as Class level variable because values of these variables are not specific to any instance but are common to all instances of a class. Such variables will be shared by all instances of an object.


1. Java Static Variable

Sample Program:

// static variable 
 
class Office{ 
   int id; 
   String name; 
   static String department ="Payroll"; 
    
   Office(int a,String b){ 
   id = a; 
   name = b; 
   } 
 void display (){
 System.out.println(id" "+name+" "+department);
 } 
 
 public static void main(String args[]){ 
 Office ab1 = new Office(101,"Gokul"); 
 Office ab2 = new Office(102,"Ram"); 
  
 ab1.display(); 
 ab2.display(); 
 } 


Output:

101 Gokul Payroll
102 Ram Payroll

2. Java Static method


// Static method

class Office{ 
     int id; 
     String name; 
     static String department = "
Payroll"; 
      
     static void change(){ 
     department = "HR"; 
     } 
 
     Office(int a, String b){ 
     id = a; 
     name = b; 
     } 
 
     void display (){System.out.println(id" "+name+" "department);} 
 
    public static void main(String args[]){ 
    Office.change(); 
 
    Office ab1 = new Office (101,"Gokul"); 
    Office ab2 = new Office (102,"Ram"); 
    Office ab3 = new Office (103,"Krishna"); 
 
    ab1.display(); 
    ab2.display(); 
    ab3.display(); 
    } 
}

Output:


101 Gokul HR
102 Ram HR
103 Krishna HR

No comments :

Post a Comment