Static Keyword

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:

  1. variable (also known as a class variable)
  2. method (also known as a class method)
  3. block

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

Static Program

 

Output

 

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

Static Program

 

Output

 

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

 

    Static Program

 

output

 

In this example of static block, static block will be going to execute first after loading class.

 

Leave a Reply

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