A guide to the static keyword in Java

Reading Time: 3 minutes

There are tons of reserve keywords in Java that cannot be use as names of variables or identifiers. One such frequently used keyword in Java is the “static” keyword. The most important reason why static keywords are heavily use in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class. However, there might be situations where you want to access only a couple of methods or variables of a class and you don’t want to create a new instance for that class just for accessing these members. This is where you can use the static keyword in Java.

static keyword is allowed for 5 things

  • Import statement
  • Class level variable
  • Class level block
  • Methods
  • Class level Inner class

static import statement

In Java 1.5 version, they introduce static import concept. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
Moreover, according to SUN microSystem, it will improve the code readability and enhance coding. But according to programming experts, sometime it leads to confusion.

static variables

  • A class level variable which has static keyword in its creation statement is called static variables.
  • JVM executes static variables bydefault means, provides memory location at the time of class loading and the it executes in the same order in which they defined from top to bottom.
  • JVM provide memory to static variables in method area.
  • static variables get life as soon as class is loaded into JVM and is available till class is removed from JVM or JVM is shutdown.
  • Moreover, its scope is class scope means it is accessible throughout the class directly by its name, and outside class by its class name provided (className.staticVariableName) if it is non-private variable.
  • Lastly, we are not allow to define static varialbes inside method or as a parameter.

static block

  • static block is a class level nameless block that contains only static keyword in its prototype.
  • The reason why it required is, if we want to execute logic only at the time of class loading, use static block.
  • Logic allowed inside staic block
    • Initializing static variables
    • Registering native libraries
    • To know classes loading order, etc

static methods

  • Static method is a method which has static keyword in its definition.
  • Fistly, no need to create any instance of class to call this method, we can call using className.staticMethodName
  • Secondly, JVM does not execute static method by itself except main method. They are executed only if they are called explicitly either from main method, or from static variables as its assignment statement or from static block.
  • Lastly, all static methods logic is persist in method area and that logic executes in java stack area in main thread by creating separate stack frame.

static inner/ nested class

  • A static class is a class that is created inside a class, is called a static nested class in Java.
  • It can be access by outer class name.
  • It can access static data members of the outer class, including private.
  • The static nested class cannot access non-static (instance) data members and methods.

static keyword control flow

public class Class10StudentDetail {

    private static int class10ACount = 10;
    private static int class10BCount = 20;
    private static int totalClass10Count;
    static {
         totalClass10Count = fullDetail();
    }


    public static void main(String[] args) {
        System.out.println("Total class 10th students count : " + totalClass10Count);
    }

    public static int fullCount() {
        return class10ACount + class10BCount;
    }
}
  • Above is an code example which contains static variables, static method and static block.
  • When the classloader loads this class, jvm will execute static variables and static block in the order they are define.
  • Firstly, the jvm execute the static variable class10ACount and create memory with default value based on datatype and then if the initialization is available on the same line then it’ll initialize with that value (which is 10 in above example).
  • Secondly, the jvm execute the static variable class10BCount and create memory with default value based on datatype and then if the initialization is available on the same line then it’ll initialize with that value (which is 20 in above example).
  • Thirdly, the jvm execute the static variable totalClass10Count and create memory with default value based on datatype and now for this variable we don’t have initialization then leave it with default value.
  • Now JVM execute the static block (if static block is define in between static variables then it will execute in between, based on the order it define), and we are initializing the variable totalClass10Count by calling static method fullCount() (as static method is not called by default by JVM, expect main method).
  • Finally, JVM execute main method which is printing the totalClass10Count variable value in console.

For JVM- Runtime Data Area :
https://blog.knoldus.com/full-explanation-of-jvm-runtime-data-area-and-how-jvm-using-it/
For JVM Architecture :
https://blog.knoldus.com/how-the-new-jvm-works-and-its-architecture/


Knoldus-blog-footer-image

Written by 

I'm having 2.5+ years of experience in Java technologies. I have worked on Java SE, Java EE, Spring, Hibernate, Kafka, Apache Beam, SQL, Scala, etc. I am curious about learning new technologies.