2017-05-02

java static keyword best explanation

Java static keyword:
              static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

The static can be used in:

  • variable
  • method
  • block
  • nested class

Example:

  • class Test{
  • static int a = 10;
  •          int b = 10; 
  • public static void main(String args[]){
  • Test t1 = new Test();
  • Test t2 = new Test();
  • Test t3 = new Test();
  • }
  • }

From the above example, static variable  are same for all the instance of the class. For Non static every instance of class object create its own local copy, 
static variable are take one memory block for instance of the classes. It makes your program memory efficient.


Example:

public class StaticExample {
static int a=10;
int b=10;
public static void main(String[] args) {
StaticExample staticExample1=new StaticExample();
StaticExample staticExample2=new StaticExample();
StaticExample staticExample3=new StaticExample();


staticExample1.a=1;
staticExample1.b=1;
System.out.println(staticExample1.a+" "+staticExample1.b);


staticExample2.a=2;
staticExample2.b=2;
System.out.println(staticExample2.a+" "+staticExample2.b);

System.out.println(staticExample3.a+" "+staticExample3.b);



System.out.println(staticExample1.a+" "+staticExample1.b);
System.out.println(staticExample2.a+" "+staticExample2.b);
System.out.println(staticExample3.a+" "+staticExample3.b);



}

}

In above Example, Non static for every instance of class object create its own local copy.




No comments:

Post a Comment