Pages

Static Keyword

What is the Static Keyword?

Static:
  • Variable declared using static keyword, it is known as a static variable.
  • The static variable will be shared with all objects(not unique for each object).
  • The memory will be created to a static variable only once at the time of class loading.

Static Keyword
Static Keyword
Demo on Static keyword:

public class StaticDemo {

int i = 0; // variable
static int j = 0; // static variable

StaticDemo() {
i++;
j++;
}

public static void main(String args[]) {
StaticDemo sd = new StaticDemo();
System.out.println("Static variable value=" + sd.j);
System.out.println("Non Static variable value=" + sd.i);

StaticDemo sd1 = new StaticDemo();
System.out.println("Static variable value=" + sd1.j);
System.out.println("Non Static variable value=" + sd1.i);

StaticDemo sd2 = new StaticDemo();
System.out.println("Static variable value=" + sd2.j);
System.out.println("Non Static variable value=" + sd2.i);
}
}
Output:

Static Keyword
Static Keyword
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.