You are here
Home > java >

Static Keyword in Java : All Scenarios

Static Keyword in Java : All ScenariosThe understanding of static keyword is so important that we as a java programmer can not imagine a single runnable program in java without a static keyword. If we want to run a small program, we must use either main() method or a static variable/block till JDK 1.6. Even we don’t have the static variable/block option to run the program starting JDK 1.7 onward. Therefore, we should know all about the static keyword and keep in mind the gist of ‘Static Keyword in Java : All Scenarios’.

We as a Java developer can’t left static keyword untouched. Hence, we should have a clear understanding of it mandatorily. Additionally, this is an important topic in the interview for the Java learners as well as professionals.

Here we will cover static keyword in java with all scenarios including latest version enhancements of JDK software. Now let’s get into the topic ‘Static Keyword in Java : All Scenarios’.

What is static in Java ?

static is a keyword in java, we can use it with class level members. These members will have only one copy of the memory in their life time irrespective of the number of objects we create. It provides separate memory for each member in the class. Static members will get the memory allocation at the time of class loading itself.

Where can we apply static keyword in Java?

We can apply static keyword in java in following places:

1) Static variable

2) Static method

3) Static block

4) Main method (mandatory to apply static keyword)

5) Static Inner class

6) Static import statement (from JDK 1.5 onward)

7) Static method in Interface ((from JDK 8 onward)

Static Variable

Static variable is a class level variable which has static keyword in its declaration. A static variable gets memory as soon as JVM loads the class till the JVM shuts down. It is accessible throughout the class directly or by its class name and even outside the class by its class name if it is not declared private. We can’t define a static variables in a method as they are class level variables.

Note: We can’t declare a local variable(variable declared inside a method) and method parameters as static. 

Static Method

Static method is a method which has static keyword in its definition. JVM doesn’t execute static methods by itself. They are explicitly executed only on call from main method or from another method (static or non-static) or from static block or from static variable as it’s assignment statement as shown in the below code snippet.

public class StaticExample {

    //method call from static variable as it's assignment statement
    private static int i = m3(); 

    static {
      m1(); //method call from static block
      System.out.println("Static block");
    }

    public static void m1() {
       m2(); //method call from another static method
       // accessing static variable directly without class name
       System.out.println(AllAboutStatic.i); 
       System.out.println("Static method m1()");
    }

    public static void m2() {
       System.out.println("Static method m2()");
       // accessing static variable with class name from static method
       System.out.println(AllAboutStatic.i); 
    }

    public static int m3() {
       return 10;
    }

    public void m4() {
       // accessing static variable with class name from non-static method
       System.out.println(AllAboutStatic.i); 
       m3(); //method call from another non-static method
    } 

    public static void main(String[] str) {
       m1(); m2(); //method call from main method
       System.out.println("main() method");
    }
}

When we want to execute a method without creating object, we should define a method as static.

Note : We can call a static method from any method(static or non-static) while we can’t call a non-static method from a static method.

Static Block

Static block is a class level nameless block “{ }” with only static keyword. It executes logics only at the time of class loading by JVM. Static block is always executed before the main method. Generally, we use them when we want to initialize static variables or to register some resources or to implement some business logic which are necessary to load before program execution.

main() method

Since main() method is the first point of the program execution, it should be active at the time of class loading. Hence main() method contains static as mandatory keyword in its definition. Suppose we wrote a class Sample.java then JVM will create a statement Sample.main(new String[0]) to execute the program.

Can we execute main() method at the time of class loading?

Yes we can execute the main() method at the time of class loading itself by calling it from static block.

Static Inner Class

Static Inner Class is a class level inner class that has static keyword in its declaration. It creates an inner object common to all instances of an outer object. We can access Static inner class by outer class name. It can access static data members of outer class even private members. Static nested class cannot access non-static (instance) variables or methods. Below code snippet is an example of static inner class.

class Outer {

    static int i = 24;

    static class Inner {
       void m1() {
       System.out.println("i is " + i);
       }
    }

    public static void main(String args[]) {
       Outer.Inner obj = new Outer.Inner();
       obj.m1();
    }
}

 

Static Import Statement (JDK 1.5)

This is an import statement that has static keyword at the beginning. It’s usage is to access static variables, static methods & static inner classes of a class from other classes without using class name. For example, below code snippet is for usage of static import statement.

import static java.lang.Math.*;

public class StaticImportTest {

    public static void main(String args[]) {

       System.out.println("Square root of 4 is :" +sqrt(4));

       //Below code without using static import
       System.out.println("Square root of 4 is :" +Math.sqrt(4));
    } 
}

Static method in interface (JDK 8)

JDK 8 onward static methods can be defined in an interface. This static method will have a method body in the interface as opposed to other abstract methods.  We can define static methods inside interfaces to use them as general utility methods. Implementing classes will not be forced to implement static methods in this case.

interface A {
   public static void m1(){
      System.out.println("I am introduced in Java 8");
   }
}

For more details on static methods inside interface, you can visit here.

What is the order of execution of static members in a class?

Once JVM loads the class, it allocates memory to static variables with their default values from top to bottom in the order they are existing in the class. Then it executes static variable’s assignment statements & static blocks logics in the order they are placed in the class. At the end main() method is called & executed. Static methods & Static inner classes are executed only when they are invoked explicitly.

That’s all about ‘Static Keyword in Java : All Scenarios’. For more details on static & other keywords in java, kindly visit Oracle docs link.

close

2 thoughts on “Static Keyword in Java : All Scenarios

Leave a Reply

Top