Home » Java Tutorial » Java Static Keyword

Java Static Keyword


Reading Time - 19 mins

In Java, static is a keyword that we mainly use to manage memory. In this tutorial, we will discuss in detail how to use the static keyword in Java and its different purpose. We will also discuss about Java Static Class, Java Static Method, and Java Static Variables in this tutorial.

What is Java static keyword

We use Java static keyword mainly when we want to access the members without creating an instance of the class. This means the static members are part of the class and does not belong to the class instance. We can use the Java static keyword for the following:

  • Block
  • Variable
  • Method
  • Class

Whenever we create the above with static keyword, we can directly access them without creating an object. We need to precede with the java keyword static in the declaration. Static members share the memory for any instance of the class and hence we say that we use it to manage memory.

In Java, we always label the main method with the java static keyword because we can use it directly and it loads along with the class.

Let us discuss each of them in detail.

Java Static block

When a block contains the name as java keyword static, we call it a static block. We use static block when we want to initialize any static members while loading the class. It first executes this static block before it calls the main method. We can understand this further with an example below.

Syntax:

static {
//code
}

Example of a single static block

We have created a single static block with a print statement and static variable i value assignment. Now during execution, when the class loads, first it executes the static block where it prints the statement and then assigns the value to the variable i. After this, it calls the main method and executes the remaining statements. This is the reason that first, it prints “Inside static block” and then it prints “Inside main method”

public class StaticBlockExample {
  static int i;
  static {
    System.out.println("Inside the static block");
    i = 10;
  }
  public static void main(String[] args) {
    System.out.println("Inside the main method");
    System.out.println("Value of i: " + i);

  }

}
Inside the static block
Inside the main method
Value of i: 10

Example of multiple static blocks

We can also create multiple static blocks in Java. It executes in the same order as it is written in the program. In the below example, we can see that in the output it prints the String value as “Good evening” as the value in static block 1 is overridden by the value in static block 2. Similarly the same is the reason for the integer value.

public class MultipleStaticBlockExample {
  
  static String value;
  static int number;
  
  static {
    System.out.println("Inside the static block 1");
    value = "good afternoon";
    number = 30;
  }

  static {
    System.out.println("Inside the static block 2");
    value = "good evening";
    number = 20;
  }
  public static void main(String[] args) {
    System.out.println("Inside the main method");
    System.out.println("String value: " + value);
    System.out.println("Integer value: " + number);
  }

}
Inside the static block 1
Inside the static block 2
Inside the main method
String value: good evening
Integer value: 20

Now let’s move on to understand the static variable.

READ  String Format Java

Java Static Variables

When we declare a variable with the java static keyword before the variable name, we call it a static variable. Static variables are public and generally belong to the class rather than the instance of the class. Hence these are also called Class variables. We can directly access these static variables without using any object which is in contrast to the non-static variables that require an object to access them. Static variables share the same memory for any instance of a class that is created. These variables are stored in a space called Metaspace in the JVM memory pool.

If a program contains both static blocks and variables, then it executes them in the same order in which it is present.

Syntax:

static datatype variable_name;

//Example
static int i;

Example of Static variable with multiple objects

Consider the below example where we have a class named Student. We have also declared 1 static variable college and 2 non-static variables name and dept. Inside the static block, we have initialized the static variable. Now during execution when the class loads, it initializes this static variable first and then calls the main method where it invokes the constructor. We have 2 separate Student objects s1 and s2 with different name and dept. But if you notice in the output college value is the same for both the objects. This is because the static variable shares the same value for all class instances and memory is allocated only once.

Java Static keyword

public class Student{

  static String college;
  public String name;
  public String dept;
  
  static {
    System.out.println("Static Block");
    college = "BITS";
  }
  
  Student(String name, String dept){
    this.name = name;
    this.dept = dept;
  }
  
  public static void main(String[] args) {
    Student s1 = new Student("Harsh", "IT");
    Student s2 = new Student("Kiran", "CSE");
    System.out.println(s1.name + " " + s1.dept + " " + college);
    System.out.println(s2.name + " " + s2.dept + " " + college);

  }

}
Static Block
Harsh IT BITS
Kiran CSE BITS

Example of Static variable using counter

Now we will see the difference between static and non-static variables which will help you understand the concept better. We have created a static variable counter and a non-static variable count both initialized to value 0. In the constructor, we increment both the values and print them. Now. when we create the first object, it prints both the values as 1. When we create the second object, the non-static variable is initialized again and hence the value will be still 1 but the static variable holds the same memory and hence value will be incremented to 2. This is because static variables are initialized only once during the loading of the class and are common for all the objects. Hope now we have understood the static keyword in java with respect to variables clearly.

public class StaticCounter {
  static int counter = 0;
  public int count = 0;
  
  StaticCounter(){
    counter ++;
    count ++;
    System.out.println("Static Counter: " + counter);
    System.out.println("Non static Count: " + count);
  }
  public static void main(String[] args) {
    StaticCounter sc1 = new StaticCounter();
    StaticCounter sc2 = new StaticCounter();
    
  }

}
Static Counter: 1
Non static Count: 1
Static Counter: 2
Non static Count: 1

Next, we will move on to static methods.

READ  Aggregation in Java

Java Static Method

When we use the java static keyword before any method, then we call it a static method. A static method does not require any class instance to access it and it belongs to a class rather than the object. We can directly access these methods and also access the static variables within this method to change its value. One best example of a static method in Java is the main method.

Below are the restrictions of using a static method:

  • We cannot access non-static members within a static method
  • Cannot call any non-static methods from a static method
  • Cannot use super keyword within a static method

Syntax:

static return_type method_name() {
//code
}

//Example
static void display() {
//code
}

Now let us see an example of using a static method along with the static variables. We have a non-static method displayValue with an instance variable initialization and a static method display with static variable initialization. Within the main method, we don’t need an object to access a static method.

public class StaticMethodDemo {
  
  static int a;
  public String value;
  
  //Non Static method
  public void displayValue() {
    value = "Java";
    System.out.println("String value: " + value);
  }
  
  //Static Method
  static void display() {
    a = 10;
    System.out.println("Value of a: " + a);
  }

  public static void main(String[] args) {
    StaticMethodDemo s = new StaticMethodDemo();
    display();
    s.displayValue();

  }

}
Value of a: 10
String value: Java

Now, consider that we call a non-static method and access an instance variable from a static method. We will get the below compilation error.

public class StaticMethodDemo {
  
  static int a;
  public String value;
  
  //Non Static method
  public void displayValue() {
    value = "Java";
    System.out.println("String value: " + value);
  }
  
  //Static Method
  static void display() {
    a = 10;
    System.out.println("Value of a: " + a);
    value = "Hello";
    displayValue();
  }

  public static void main(String[] args) {
    StaticMethodDemo s = new StaticMethodDemo();
    display();
    s.displayValue();

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
  Cannot make a static reference to the non-static field value
  Cannot make a static reference to the non-static method displayValue() from the type StaticMethodDemo

  at StaticMethodDemo.display(StaticMethodDemo.java:16)
  at StaticMethodDemo.main(StaticMethodDemo.java:22)

Lets, move on to understand static class.

READ  Do-While Loop in Java

Java Static Class

If we create a class with prefix as a java static keyword, we call it a static class. We can use static class only for nested classes ie. a class within another class. Only inner classes can be made as a static class.

Features of a static class

  • Can access only static variables of the outer class
  • Cannot access other non-static variables or non-static methods of the outer class.
  • A static class can contain non-static methods.
  • We don’t need to create an object for the static class if we need to access a static method of that class.
  • We cannot declare the outer class as static and can use a java static keyword only for the inner class.

Syntax:

public class classname {
  static class innerclassname {

  }
}

Now let’s see various examples of using the nested static class.

Example of static class with a non-static method

In this example, we have a nested static class Inner with a non-static method display. Inside this method, we can access the static variables of the Outer class directly. In order to call this method from the Outer class main method, we need to create an object of the inner class, since the method is non-static. This is not required if we create a static method. We will see this in the next example below.

public class OuterClass {
  static int i = 5;
  
  static class Inner {
    public void display() {
      i ++;
      System.out.println(" Value of i: " + i);
    }
  }

  public static void main(String[] args) {
    OuterClass.Inner i = new OuterClass.Inner();
    i.display();

  }

}
Value of i: 6

Example of static class with a static method

Now let’s see how to call a static method of a static class from the main method. Since the method is static, we can access the method from the main by directly using the inner class name as seen in the below example.

public class OuterClass {
  static int i = 5;
  
  static class Inner {
    
    static void display() {
      i++;
      System.out.println("Value of i: " + i);
    }
  }

  public static void main(String[] args) {
    OuterClass.Inner.display();

  }

}
Value of i: 6

Example of all Java static members

To summarize below is an example that covers all the java static keyword members like block, variable, method, and class.

public class StaticExample {

  static int number;
  public String value;
  
  static {
    number = 5;
    System.out.println("Value of number inside static block: " + number);
  }
  
  public void displayString() {
    value = "Hello";
    System.out.println("Value of string: " + value);
    number =20;
    System.out.println("Value of number inside Outer class method: " + number);
  }
  
  
  static class Inner {
    static void display() {
      number = 10;
      System.out.println("Value of number inside static class method: " + number);
    }
  }
  
  public static void main(String[] args) {
    StaticExample s = new StaticExample();
    StaticExample.Inner.display();
    s.displayString();

  }

}
Value of number inside static block: 5
Value of number inside static class method: 10
Value of string: Hello
Value of number inside Outer class method: 20

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions