elibraryportal Logo

Static Keyword in Java

static keyword is mainly used for memory management. We can be use with .

  • Variables
  • Methods
  • Blocks
  • Nested classes. e.t.c

1) Static Variable in Java

→ When a variable is declared as static, it is called static variable.

→ static variable refer to the common property of all objects.

→ static variable gets memory only once in the class area at the time of class loading.

Example 1:

Output

Static Variable in Java

Example 2: Change the course.

Output

Static Variable in Java

2) static method in Java

  • static method can access the static data member and can change the value of it.
  • When a method is declared with the static keyword, it is known as a static method.

Example : Change the course.

Output

static method in Java

3) Static block in Java

  • Is used to initialize the static data member or static variables..
  • Static block is executed once when the first object of the class is created.
  • It is executed before the main method at the time of classloading.

Example :

Output

static Block in Java