Saturday, July 11, 2015

Explain "static" keyword

a.       static is a keyword in java which is used as a modifier for variables and methods within a class. static means something which belongs to the class and not to every object. If a property is static, only 1 copy is maintained for that property per class. Separate copies are not created for every object. Similary static methods are also invoked on the class and not on objects. Since static methods are not invoked on objects, we cannot use “this” keyword within static methods. Syntax of using static variables and methods is

ClassName.variable= value  (or)  ClassName.method();

In java we also have a concept of a static block which is written within a class. A static block of code is executed when the class is initially loaded by the class loader of jvm.

How to declare static?
 class A{
      static int I;           // static variable
      static void m1(){
                                      // static method
}
      static{
                                      // static block
}
}
How to use?
A.i=5;                          // assigning value to static variable: ClassName.variable
A.m1();                       //invoking a static method: ClassName.method()
     

A static variable is often called as a class variable as it is a property of the class. A static method cannot use instance variables. It can use static variables only. Static variables are often used to count the number of objects created or to manage some global constant accessible from anywhere by using the class name. Also write a simple code to show use of static. 

No comments:

Post a Comment