What is static keyword in java


As discussed, everything in java is class and objects. The variables and methods of the class can be accessed using object.
consider the example below

public class SampleClass{
     public static void main(){
           SampleClass exp=new exp();
            exp.add();
}
   void add(){
          int a=10;
int b=a+10;
      System.out.println("The value of b is"+b):
}
}

In the  above example, add() method  is called using  the object created.
If the variables/method needs to be accessed using class name, it will achieved by means of static keyword.
Consider the below example
public class Samplestat {
static int value=10;

static void PrintValue(){
System.out.println("value of the variable is "+value);
}

public static void main(String args[]){
Samplestat.PrintValue();

}
}

In the above example,PrintValue() method is called using the classname without creating the object.

Points to be noted about static variable.
   
i] static variable is applicable to class variables or methods or block of code
ii] static methods or block of code can only call static method or static variable
iii] static methods or variable or block of code can be loaded  first in the JVM.Hence it is not related to object.It is common to all objects.Hence it is global
iv] The variables marked with static are global variables.
iv] "this" or "super" keywords cant be used in static methods as these keywords are related to objects. [Will discuss in detail in upcoming posts]
v] As main method will be used for starting the java program it needs to be loaded first. Hence it should be declared as static.


 
Previous
Next Post »