Static keyword in Java

  • In order to use the variables and methods of a class, an object need to be instantiated. But when we use “static” keyword on variables and methods, these variables and methods can be accessed without creating an object.
  • A variable declared as static is called as class variable or static variable.
  • A method declared as static is called as class method or static method.
  • Apart from static variable and static method , there is static class and static block.
  • A static block is executed just before the execution of a main method.
  • Only a nested class is declared static and can be accessed without instantiating the object of an outer class.

Why do we use static in public static void main(String args[]) in Java?

A variable or method is not accessible until we create a new object and call the method using that object. But the JVM wants to access the main method without creating an object of the class containing main method. Thats why we always declare a main method as static.

What is static block :

  • A static block contains a set of codes enclosed within braces.
  • A static block is executed before the execution of main method.
  • It is used to initialize the static variables of a class and are executed only once when the class is loaded into the JVM.
  • If there are more than one static block in a class, then they are executed in the order in which they are written.

Example : 


Output : 

Inside static block

Share this website !!!
Facebook Twitter Linkedin