Static Keyword in Java

In this tutorial you will learn about static keyword in Java with example code.

Static keyword in java mainly used for memory management process.

In Java static keyword can be used in following cases.

  1. With Variables
  2. With Methods
  3. With Blocks
  4. With Nested Class

Lets discuss each of them one by one.

Static Keyword in Java

Static Variable in Java

We can declare static variable by simply writing static keyword before normal variable. Static variables are memory efficient as memory for it is allocated only once while class loading. So the value stored in that variable is same for all the methods and objects.

If any method changed that variable value, remaining all methods get updated value.

Example:

Output

Bahubali collection upto now is 1 crores
Bahubali collection upto now is 2 crores
Bahubali collection upto now is 3 crores

Note: Try to remove static keyword and run the program to know the use of static keyword.

We can access static variables in three ways, using object, using class name and directly.

Static Method in Java

Static methods are methods which can be called and executed without creating the objects. A very basic and simple example to this is main() method. JVM directly calls main() method without creating object of class. It saves lot of memory and that is the reason main() method is static in Java.

Example:

Output

Our present prime minister is N Modi

Important points about static method:

  • Java static methods belongs to class but not instances of the class.
  • Static method cannot access non-static members directly.
  • this and super keywords cannot be used in static method.

Static Block in Java

If we use static keyword to declare a block then that block is called static block.

Syntax:

If we want to initialize any static data members in program, we can write those in static block to give higher priority in the program. Because static block will first executed.

Whenever program starts running, JVM first executes static block if any and then only search for main() method.

Example:

Output

Hello user, this is before main method
Now entered into the main method

Static Nested Class in Java

When we create a class inside another class using static keyword then it is called static nested class.

We can access static members (including private members) of outer class inside static nested class.

We cannot access non-static members of outer class inside static nested class

Example:

Comment below if you have queries or found something incorrect in above tutorial for static keyword in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *