You are here
Home > java > Core Java >

Static Keyword In Java With Examples

Static Keyword in JavaThe understanding of static keyword in java is so important that we as a java programmer cannot imagine a single runnable program without a static keyword. If we want to run a small program, we must use either main() method (which is static) 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 significance of ‘Static in Java’.

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

Here we will cover static in java with all scenarios, including latest version enhancements of the JDK software. Let’s get into the topic ‘Static In Java’.

What is static keyword in Java?

‘static’ keyword in java is a versatile keyword which is used with class level members. These members will have only one copy of the memory in their life time, no matter how many 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.

Static variables and methods are allocated memory space only once during program execution. This memory space is shared among all instances of the class. They are not tied to any specific instance.

Why do we use static keyword in Java?

The static keyword in Java serves several purposes related to memory management, code organization, and efficiency. Here are some of the common reasons when we use it:

1) Sharing data across objects: When we declare a variable as static, it becomes a class variable. There is only one copy of this variable shared among all instances of the class. This is useful for constant values (like conversion factors) or counters that need to be incremented throughout the program.

2) Creating utility methods: Static methods belong to the class itself, not individual objects. We can call a static method without creating an object, making them convenient for helper methods that don’t rely on object state. The main method, the entry point of a Java program, is a big example of a static method.

3) Memory efficiency: Since static variables are shared, only one copy exists in memory. This saves memory as compared to creating specific instances for each object.

4) Improved code organization: Static methods can promote better organization of code by grouping utility methods that don’t depend on object state within the class.

Where to use static keyword in Java?

The static keyword in Java promotes memory efficiency, improves code organization, and supports access to class-level functionalities. It is used to modify the behavior of various components of a Java program, such as variables, methods, blocks, import statements and nested classes. Here are the major places where we use the static keyword in Java:

1) Static Variables: When a variable is declared with the static keyword, it becomes a class-level variable rather than an instance-level variable. This means that the same variable is shared among all instances of the class. Static variables are commonly used to represent constants, configuration values, or shared resources across instances of a class.

2) Static Methods: Likewise, when a method is declared with the static keyword, it becomes a class-level method rather than an instance-level method. Static methods can be called directly using the class name followed by the dot, without creating an instance of the class. They are generally used for utility methods, helper methods, or operations that do not require access to instance-specific data.

3) Static Blocks: Static blocks are used to initialize static variables or perform any one-time initialization tasks when the class is loaded into memory. Static blocks are executed only once, when the class is first loaded, and they are executed in the order they appear in the source code.

4) Static Nested Classes: A static nested class is a nested class that is declared with the static keyword. Unlike non-static nested classes (inner classes), static nested classes do not have access to instance variables and methods of the outer class. They are conventionally used to logically group related classes or provide encapsulation.

5) Static Import: The static keyword is also used in static imports, allowing static members (variables and methods) of other classes to be imported directly into the current class without qualifying them with the class name. This can lead to more concise and readable code in particular situations.

Altogether, the static keyword in Java provides a mechanism for defining class-level members and behavior, supporting code reusability, performance optimization, and improved organization of code.

Where can we apply static keyword in Java?

We can apply static keyword in java in following places:

1) Static variable (Class Variable)

2) Static method

3) Static block

4) The Main method (mandatory to apply static in java main() method)

5) Static Inner class

6) Static import statement (from JDK 1.5 onward)

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

Static Variable (Class Variable)

Static variable also called Class Variable is a class level variable which has the static keyword in its declaration. They are shared among all objects of that class. 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 static variables in a method as they are class level variables.

Static variables are often used to define constants that are associated with a class.

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

public class MyClass {
   static int count = 0; // A static variable
   public static final int MAX_VALUE = 100; // A static variable or constant
}

Static Method

A static method is a method which has the 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: Static methods can only access other static methods and variable within the class. They can’t directly access non-static members (like instance variables) because they don’t operate on specific objects. On the other hand, 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 perform one-time setup tasks such as initialize static variables or to register some resources or to implement some business logic which are necessary to load before program execution. They execute only once when the class is first accessed. For example:

public class MyClass {
   static {
     // Initialize static variables here
   }
}

main() method

The main() method is one of the most popular place to use static in java. 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 a 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 the static keyword in its declaration. It creates an inner object common to all instances of an outer object. We can access the Static inner class by outer class name. It can access static data members of the outer class, even private members. A 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 the ‘static’ keyword at the beginning. Its usage is to access static variables, static methods & static inner classes of a class from other classes without prefixing the class name. For example, below code snippet is for usage of the 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 a separate article on Static Methods in Interface.

FAQ

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

Sometimes we use static keyword in java program in multiple places, then we need to understand the order of execution of the program clearly.

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.

What is the primary purpose of using static keyword in Java?

The primary purpose of using the static keyword in Java is to create class-level members that are common among all instances of the class, rather than belonging to individual object instances.

How are static methods different from instance methods in Java?

Static methods belong to the class, and we can invoke them using the class name, without creating an instance. Instance methods are associated with objects of the class and require an instance to call them.

When should we use static methods in Java?

We should use static methods when a method doesn’t depend on the state of a particular object but is relevant to the class as a whole. Common use cases include utility methods, factory methods, and methods for performing class-level operations.

Can a static method access instance variables and methods?

Static methods cannot directly access instance variables or methods because they don’t have access to a specific object’s state. However, we can access instance variables or methods by passing an object as a parameter to the static method.

What is the difference between a static nested class and a non-static (inner) class in Java?

A static nested class is associated with the outer class itself and can be instantiated without an instance of the outer class. A non-static inner class is associated with an instance of the outer class and can access its instance variables.

Can we use the static keyword in Java interfaces?

Starting with Java 8, we can define static methods in Java interfaces, that allow us to create utility methods in interfaces.

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

2 thoughts on “Static Keyword In Java With Examples

Leave a Reply


Top