Static keyword in Java

Static keyword can be used with

  1. Variables
  2. Methods
  3. Blocks
  4. Static inner class

lets see them one by one

Static Variable

Static variable can be create by adding static keyword in front of variable.

below count is static variable.

A static variable is shared among all objects of class.

Each class have their own instance variable but they all share static variables.

Static variable is also know as class variable because it belongs to class not specific to any object.

In diagram memory allocation for different variables are shown.

It also represents static variables are stored in MetaSpace( Java8 Onward ) from where all objects are sharing it.

Why Static variable required?

A static variable is shared amount all objects of class. So to share information amount objects static variable can used.

2. Static Method

To create a method static add static keyword before to method.

<access-specifier> static <return-type> <method-name>{

A static method can access only static fields and member functions.

It can not access not static fields and methods.

Why Static method can not access not static variables?

Static variable initialize when a class in loaded in JVM

Instance variable is initialized when object is created.

At the time when static method called Instance variables they are not created. Thats why static method can not access instance variable.

3. Static Block

A block is set of statements inside opening closing brackets {….}.

A static block is a block which contains static in front.

Why Static block is needed?

A static block can be used to initialize some values that a program required during load time or in throughout the program.

4. Static Inner class

A class inside a class in called nested class java supports both static and non static nested classes.

A static nested class is nested class with preceded static keyword.