What Is A Static Keyword In Java?

What Is A Static Keyword In Java?
What Is A Static Keyword In Java?

Introduction

Keywords are reserved terms in Java that cannot be used as identifiers. Java language has 57 keywords, and the static keyword in Java is one of them. 

In Java, we first make an instance of the class to access its members. However, there will be times when we will need to access class members without using variables. In these cases, the static keyword in Java can be used. We must declare class members static if we need to access them without creating an instance of the class.

Static Keyword In Java 

In Java, the static keyword is mainly used for memory management. It is a non-access modifier. It can be used with methods, variables, blocks, and nested classes. It is associated with the class rather than an instance of the class or object of a class.

In Java, the members of the Math class are static. As a result, we can access its members without having to create Math instances.

As an example: 

public class Main {
    public static void main( String[] args ) {

        // accessing the methods in java of Math class
         System.out.println("The value of pi = " + Math.PI);
         System.out.println("3^3 = " + Math.pow(3,3));
    
    }
}

Output:

The value of pi = 3.141592653589793
3^3 = 27.0

In the above example, we haven’t created any instances of the Math class. Still, we can access its variable- PI and method- pow() as the variables and methods of math class are static.

Static Keyword in Java is used in the following ways:

  • Static Variables
  • Static Methods
  • Static Block
  • Static Nested Classes
Image Source: Javatpoint

Let’s look at each of these types in more depth to understand the use of a Static Keyword in Java.

Static Variables

Static Variables in Java are also known as class variables. Any variable declared with the static keyword is referred to as a static variable. The static keyword in java denotes a variable that refers to a common attribute shared by all of the class objects.

For example, the school name is the same for its students, workers, faculty, etc. Hence, only one copy of the static variable is shared by all instances of the class. Static variables can be accessed directly from both static and non-static methods.

Let’s see how to declare static variables in Java through:

class Student{
    // Declaration of static variable
    static int age;
}
class Main {
    // Accessing the static variable
    Student.age = 16;
}

Here, we are accessing the static variable from the other class using its class name.

Example using Static Variable:

class Result {

   // static variable
   static int maxvalue = 20;
  
   // non-static variable
   int minvalue = 10;
}

public class Main {
   public static void main(String[] args) {
       Result obj = new Result();

       // access the non-static variable
       System.out.println("minvalue + 1 = " + (obj.minvalue + 1));

       // access the static variable
       System.out.println("maxvalue + 1 = " + (Result.maxvalue + 1));
   }
}

Output:

minvalue + 1 = 11
maxvalue + 1 = 21

In the above example, a non-static variable named minvalue and a static variable named maxvalue is declared inside the class Result. In the Main class, we call the non-static variable by using the object of the class (obj.minvalue + 1). However, we call the static variable using the class name (Result.maxvalue + 1).

Static Methods

Methods specified with the static keyword are known as static methods.

  • When a method is declared static, we can call or access it without creating an object or instance of the class. 
  • A static method can access and alter the value of a static data member.
  • We know that to use non-static methods, we need first to construct the class object and then call the method through the object, but we can call static methods directly with the class name, unlike non-static methods.

We use the class name to call static methods directly. As an example,

class Example {
    // static method inside the class
    public static void method() {...}
}

class Main {
    // invoking the static method
    Example.method();
}

The static function can be accessed directly from other classes using the class name, as seen above.

Note: The main method is always static in Java so that the compiler can call it before creating an object or without creating an object of a given class. As in Java, the compiler starts executing a program by considering the main method as its starting point. 

Example using Static Methods:

class Test {

    // non-static method
    int add (int a, int b){
        return a + b;
    }

    // static method
    static int multiply(int a, int b){
        return a * b;
    }
}

public class Main {

   public static void main( String[] args ) {

        // create an instance of the Test class
        Test T = new Test();

        // call the nons-tatic method
        System.out.println(" 4 + 5 = " + T.add(4,5));

        // call the static method
        System.out.println(" 4 * 5 = " + Test.multiply(4,5));
   }
}

Output:

 4 + 5 = 9
 4 * 5 = 20

In the above example, a non-static method named add() and a static method named multiply() is declared inside the class Test. Inside the Main class, we are calling the non-static method by using the object of the class (T.add(4,5)). However, we are calling the static method using the name of the class (Test.multiply(4,5)).

Static Block

Static Blocks are used to initialise the static data members or static variables. It is executed only once before the main function when the class is loaded. If the object of the class or the static members of the class is requested in code, the class is loaded.

A class can have multiple numbers of static blocks, and each of the static blocks is executed in the same manner in which they have been coded in the program.

The example for understanding the declaration of Static Block in Java:

class Student{

    // Declaring static variable
    static int age;

    // Declaring static block
    static {
        age = 20;
    }
}

Example using static blocks:

class Student {

   // static variables
   static int age = 20;
   static int x;
   static int maxvalue;

   // static blocks
   static {
       System.out.println("Static block one");
       x = age * 2;
   }
   static {
       System.out.println("Static block two");
       maxvalue = 50;
   }

   // static method
   static void show() {

       System.out.println("age =  " + age);
       System.out.println("x = " + x);
       System.out.println("maxvalue = " + maxvalue);
   }

   public static void main(String args[]) {
       // calling the static method
       show();
   }
}

Output:

Static block one
Static block two
age =  20
x = 40
maxvalue = 50

In the above example, as soon as the Main class gets loaded, the code runs in the following manner:

  • Firstly, the value of age is set to 20.
  • The static block one is executed. Hence, the string Static block one is printed, and x is set to age * 2.
  • The static block two is executed. Hence, the string Static block two is printed, and maxvalue is set to 50.
  • Finally, the statements inside the method show() are executed.

Static Nested Class

We can define a class as static; however, the class must be a nested class only i.e., the class must be present within another class before we can declare it as static. The object of the outer class is not required by the nested static class. Another limitation of the nested static class is that it cannot access the outer class’s non-static data members. 

Let’s look at an example to understand Static Nested Classes.

class Car {

   // static nested class
   static class Tyre{
       int tyre1 = 3;
       int tyre2 = 4;

       int Total_Tyres(){
           return tyre1 + tyre2;
       }
   }

}
public class Main {
   public static void main(String[] args) {

       // create an object of the nested static class
       // using the name of the outer class
,
       Car.Tyre T = new Car.Tyre();
       System.out.println("Total Tyres =  " + T.Total_Tyres());
   }
}

Output:

Total Tyres =  7

In the above example, we created a static class named Tyre inside the class Car. In the line,  Car.Tyre T = new Car.Tyre();   we are creating an object T using the name of the outer class.

Frequently Asked Questions

What is a static and non-static keyword in Java?

Static keywords in Java use compile-time binding whereas non-static keywords use run-time or dynamic binding.

What are static methods?

Static methods can access class variables (static variables) without needing a class object (instance), whereas non-static methods and variables can only be accessed via objects.

What is the difference between static and non-static variables?

Static variables are used by all instances of a class, whereas non-static methods are only specific to the particular instance of a class.

Key Takeaways

Let’s summarise all instances of a class using static variables as the key points to remember for using static keywords in Java language. 

  • We mainly use it to save memory. It can be used as variables, methods, blocks and nested classes.
  • The static variable is shared among all of the objects of a class. 
  • Static methods can access static variables without needing a class object.
  • Static Blocks are called only once when Java Virtual Machine loads the class into memory.
  • The classes in Java can be static only when it is a nested class.

By Mehak Goel