Static keyword In Java
The static keyword in java is used for memory management mainly. Static keyword can be used with class, variable, method and block. The static keyword belongs to the class that specific instance of the class.
The static can be:
- variable (also known as a class variable)
- method (also known as a class method)
Watch this video on our YouTube channel for better understanding, else, keep reading.
1) Java static variable
Static variable in Java is variable which belongs to the class and not to object. It is initialized only once at the start of the execution.
Few Important Points:
- Static variables are also known as Class Variables.
- The static variable gets memory only once in a class area at the time of class loading.
Example of static variable
The above program has a class Candidate in which we use static variable Institute. This variable is common to all candidate so we make it static using static keyword. The candidate information will be displayed with different roll no and names but same institute. The advantage to making institute variable static is that it saves memory as it loads once in a class area at class loading time:
2) Java static method
A static method can be invoked without the need for creating an instance of a class.
Example of static Method
As you can see in the above example there is no need to create an object of class Candidate it is directly called because I had to make method display as static using static keyword.
3) Java static block
Is used to initialize the static data member. It is automatically called when your class loads, i.e. when you run your program.
Example of static Block
In this example of static block, static block will be going to execute first after loading class.