Java Static Keyword

Java Static Keyword: What It Is and How to Use It

Learn how to use the Java static keyword to create class members, methods, blocks, and nested classes in Java

Introduction

Java is an object-oriented programming language that supports the concept of classes and objects. A class is a blueprint that defines the properties and behaviors of its objects. An object is an instance of a class that has its own state and can perform actions.

In Java, there are two types of members that belong to a class: instance members and static members. Instance members are those that are associated with each object of the class. They are created when an object is created and destroyed when an object is destroyed. Static members are those that are shared by all objects of the class. They are created when the class is loaded and remain in memory until the program ends.

Java Static Keyword

The static keyword in Java is used to declare static members in Java. It can be applied to variables, methods, blocks, and nested classes.



Static Variables

A static variable is a variable that belongs to the class and not to any specific object. It is also known as a class variable. A static variable is declared using the static keyword before the data type and can be accessed by using the class name followed by a dot (.) and the variable name. Alternatively, a static variable can also be accessed by using an object reference followed by a dot (.) and the variable name. However, accessing static variables using object reference is not recommended as it may cause confusion and reduce readability.

static int count; // a static variable

ClassName.variableName; // accessing a static variable using class name

objectName.variableName; // accessing a static variable using object reference

Java

Example of Static Variables

Let us see an example of how to use static variables in Java. Suppose we want to create a class called Student that represents a student in a school. Each student has a name, an age, and a roll number. We also want to keep track of the total number of students in the school. To do this, we can use a static variable called totalStudents that is shared by all objects of the Student class. Here is how we can define the Student class:

public class Student {
  
  // instance variables
  String name;
  int age;
  int rollNo;

  // static variable
  static int totalStudents = 0;

  // constructor
  public Student(String name, int age, int rollNo) {
    this.name = name;
    this.age = age;
    this.rollNo = rollNo;
    totalStudents++; // increment the static variable by 1
  }

  // method to display the details of a student
  public void display() {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Roll No: " + rollNo + "\n");
  }
}
Student.java

Now, let us create some objects of the Student class and display their details and the value of the static variable totalStudents:

public class Main {
  
  public static void main(String[] args) {
    
    // create three objects of the Student class
    Student s1 = new Student("Alice", 18, 101);
    Student s2 = new Student("Bob", 19, 102);
    Student s3 = new Student("Charlie", 20, 103);

    // display the details of each student
    s1.display();
    s2.display();
    s3.display();

    // display the value of the static variable totalStudents
    System.out.println("Total Students: " + Student.totalStudents);
  }
}
Main.java

The output of the above code is:

Name: Alice
Age: 18
Roll No: 101

Name: Bob
Age: 19
Roll No: 102

Name: Charlie
Age: 20
Roll No: 103

Total Students: 3
CMD

As we can see, the static variable totalStudents is incremented by 1 every time a new object of the Student class is created. It is also accessed by using the class name Student followed by a dot (.) and the variable name totalStudents.

Can we declare a variable with var as static in Java?

No, the ‘var‘ keyword in Java is used for local variable type inference and cannot be used in conjunction with ‘static’ to declare class-level variables.

Benefits of Static Variables

Some of the benefits of using static variables are:

  • They can be used to store common data that is shared by all objects of a class, such as constants, counters, etc.
  • They can be used to optimize the memory usage of the program, as only one copy of the static variable is created and maintained in memory, regardless of the number of objects of the class.
  • They can be accessed without creating an object of the class, which can be useful for utility or helper methods.

Limitations of Static Variables

Some of the limitations of using static variables are:

  • They are not part of the state of the object, which means they do not reflect the individual characteristics or behaviors of the object.
  • They can cause concurrency issues in multithreaded environments, as multiple threads can access and modify the same static variable at the same time, leading to inconsistent or unexpected results.


Static Methods

A static method is a method that belongs to the class and not to any specific object. It is also known as a class method. A static method is declared using the static keyword before the return type. A static method can be accessed by using the class name followed by a dot (.) and the method name. Alternatively, a static method can also be accessed by using an object reference followed by a dot (.) and the method name. However, accessing static methods using object reference is not recommended as it may cause confusion and reduce readability.

static returnType methodName(parameters) {
  // method body
}

ClassName.methodName(arguments); // accessing a static method using class name

objectName.methodName(arguments); // accessing a static method using object reference

Java

Example of Static Methods

Let us see an example of how to use static methods in Java. Suppose we want to create a class called MathUtils that provides some utility methods for performing mathematical operations. To do this, we can use static methods that can be accessed without creating an object of the MathUtils class. Here is how we can define the MathUtils class:

public class MathUtils {
    
    // static method to calculate the factorial of a number
    public static int factorial(int n) {
        // base case
        if (n == 0 || n == 1) {
            return 1;
        }
        // recursive case
        return n * factorial(n - 1);
    }

    // static method to calculate the power of a number
    public static int power(int x, int n) {
        // base case
        if (n == 0) {
            return 1;
        }
        // recursive case
        return x * power(x, n - 1);
    }
}
MathUtils.java

Now, let us use the static methods of the MathUtils class in the main method:

public class Main {
  
  public static void main(String[] args) {
    
    // use the static methods of the MathUtils class
    System.out.println("Factorial of 5: " + MathUtils.factorial(5));
    System.out.println("Power of 2 to the 3: " + MathUtils.power(2, 3));
  }
}
Main.java

The output of the above code is:

Factorial of 5: 120
Power of 2 to the 3: 8
CMD

As we can see, the static methods of the MathUtils class are accessed by using the class name MathUtils followed by a dot (.) and the method name.

Benefits of Static Methods

Some of the benefits of using static methods are:

  • They can be used to provide utility or helper methods that do not depend on the state of the object, such as mathematical operations, string manipulation, etc.
  • They can be used to access or modify static variables of the class, as they are in the same scope.
  • They can be accessed without creating an object of the class, which can be useful for performance or convenience reasons.

Limitations of Static Methods

Some of the limitations of using static methods are:

  • They cannot access instance variables or methods of the class, as they are not associated with any specific object.
  • They cannot use the this or super keywords, as they do not refer to any object.
  • They cannot be overridden by subclasses, as they are resolved at compile-time and not at run-time.


Static Blocks

A static block is a block of code that is executed only once when the class is loaded. It is also known as a static initializer. A static block is declared using the static keyword before the opening curly brace, as shown below:

static {
  // block of code
}
Java

A static block can be used to initialize static variables or perform any other operations that need to be done only once for the class. A class can have multiple static blocks, which are executed in the order they appear in the class.

Example of Static Blocks

Consider a Configuration class aiming to initialize static variables storing configuration parameters for a software application. Utilizing a static block, these variables can be set during class loading:

public class Configuration {

    // Static variables for configuration
    static int timeout;
    static String serverAddress;

    // Static block to initialize configuration parameters
    static {
        timeout = 5000; // Set default timeout
        serverAddress = "https://api.example.com"; // Set default server address
        // Additional setup or configuration logic if needed
    }

    // Method to update server address
    public static void setServerAddress(String address) {
        serverAddress = address;
    }

    // Method to retrieve server address
    public static String getServerAddress() {
        return serverAddress;
    }

    // Method to update timeout value
    public static void setTimeout(int newTimeout) {
        timeout = newTimeout;
    }

    // Method to retrieve timeout value
    public static int getTimeout() {
        return timeout;
    }
}
Configuration.java

Now, let’s utilize the Configuration class within a Main class to demonstrate its functionality:

public class Main {
  
  public static void main(String[] args) {
    
        System.out.println("Default Server Address: " + Configuration.getServerAddress());
        System.out.println("Default Timeout: " + Configuration.getTimeout() + "\n");

        Configuration.setServerAddress("https://api.updatedexample.com");
        Configuration.setTimeout(3000);

        System.out.println("Updated Server Address: " + Configuration.getServerAddress());
        System.out.println("Updated Timeout: " + Configuration.getTimeout());
  }
}
Main.java

This example showcases how a static block within the Configuration class initializes default configuration values. The Main class further demonstrates the retrieval and modification of these static variables.

The output of the above code is:

Default Server Address: https://api.example.com
Default Timeout: 5000

Updated Server Address: https://api.updatedexample.com
Updated Timeout: 3000
CMD

As we can see, the static block within the Configuration class gets activated as the class is loaded, setting up default configuration values. Using the class methods later illustrates how these fixed variables can be adjusted, effectively controlling the application’s settings.

Benefits of Static Blocks

Some of the benefits of using static blocks are:

  • They can be used to initialize static variables that require complex logic or operations, such as reading from a file, loading a driver, etc.
  • They can be used to perform any one-time tasks that are related to the class, such as registering a listener, creating a singleton instance, etc.
  • They can be executed without creating an object of the class, which can be useful for performance or convenience reasons.

Limitations of Static Blocks

Some of the limitations of using static blocks are:

  • They cannot access instance variables or methods of the class, as they are not associated with any specific object.
  • They cannot use the this or super keywords, as they do not refer to any object.
  • They cannot throw checked exceptions, as they are not part of any method signature. You would typically need to handle the checked exception within the block using a try-catch construct.


Static Nested Classes

A static nested class is a class that is defined inside another class and has the static modifier. It is also known as a static inner class. A static nested class is declared using the static keyword before the class keyword. A static nested class can be instantiated without creating an object of the outer class.

class OuterClass {
  // outer class members

  static class InnerClass {
    // inner class members
  }
}

// Instantiating static nested class
OuterClass.InnerClass innerObject = new OuterClass.InnerClass();

Java

A static nested class can access the static members of the outer class, but not the instance members. A static nested class can also have its own static and instance members, as shown below:

class OuterClass {
  // outer class members

  static class InnerClass {
    // inner class members

    static int staticVar; // static variable of the inner class
    int instanceVar; // instance variable of the inner class
  }
}
OuterClass.java

Example of Static Nested Classes

Let us see an example of how to use static nested classes in Java. Suppose we want to create a class called Car that represents a car. Each car has a model, a color, and an engine. The engine is another class that has its own properties, such as type, power, and fuel. To model this relationship, we can use a static nested class called Engine inside the Car class, as shown below:

public class Car {
    
    // instance variables of the Car class
    String model;
    String color;
    Engine engine; // an object of the Engine class

    // constructor of the Car class
    public Car(String model, String color, String type, int power, String fuel) {
        this.model = model;
        this.color = color;
        this.engine = new Engine(type, power, fuel); // create an object of the Engine class
    }

    // method to display the details of the car
    public void display() {
        System.out.println("\nModel: " + model);
        System.out.println("Color: " + color);
        System.out.println("Engine Details:");
        engine.display(); // call the display method of the Engine class
    }

    // static nested class Engine
    static class Engine {
        
        // instance variables of the Engine class
        String type;
        int power;
        String fuel;

        // constructor of the Engine class
        public Engine(String type, int power, String fuel) {
            this.type = type;
            this.power = power;
            this.fuel = fuel;
        }

        // method to display the details of the engine
        public void display() {
            System.out.println("Type: " + type);
            System.out.println("Power: " + power + " HP");
            System.out.println("Fuel: " + fuel);
        }
    }
}
Car.java

Now, let us create some objects of the Car class and display their details in the main method:

public class Main {
  
  public static void main(String[] args) {
    
        // create two objects of the Car class
        Car c1 = new Car("Honda Civic", "Silver", "Petrol", 180, "Unleaded");
        Car c2 = new Car("Tesla Model 3", "Red", "Electric", 250, "Battery");

        // display the details of each car
        c1.display();
        c2.display();
  }
}
Main.java

The output of the above code is:

Model: Honda Civic
Color: Silver
Engine Details:
Type: Petrol
Power: 180 HP
Fuel: Unleaded

Model: Tesla Model 3
Color: Red
Engine Details:
Type: Electric
Power: 250 HP
Fuel: Battery
CMD

As we can see, the static nested class Engine is used to define the properties and behaviors of the engine of the car. The Car class can access the instance variables and methods of the Engine class by using the engine object. The Engine class can also be instantiated without creating an object of the Car class, as shown below:

Car.Engine e1 = new Car.Engine("Diesel", 200, "Diesel");
Java

Benefits of Static Nested Classes

Some of the benefits of using static nested classes are:

  • They can be used to group related classes that are only used within the outer class, such as helper classes, data structures, etc.
  • They can provide better encapsulation and readability, as they can hide the implementation details of the inner class from the outside world.
  • They can improve the performance and memory efficiency of the program, as they do not need a reference to the outer class object.

Limitations of Static Nested Classes

Some of the limitations of using static nested classes are:

  • They cannot access instance variables or methods of the outer class, as they are not associated with any specific object.
  • They cannot use the this or super keywords, as they do not refer to any object.
  • They can cause confusion and complexity, as they introduce another level of nesting and scoping.


Common Error: Accessing Non-Static Members in a Static Context

Attempting to access non-static variables or methods directly within a static context results in a compilation error. When accessing non-static elements like variables or methods within a static context, such as a static method, the error occurs because static contexts don’t have direct access to instance-specific elements. Non-static elements belong to specific object instances, and static contexts belong to the class itself.

Error: non static variable cannot be referenced from a static context | non static method cannot be referenced from a static context.

public class MyClass {

    int nonStaticVar = 10;

    public static void myStaticMethod() {
        System.out.println(nonStaticVar);
        nonStaticMethod();
    }

    public void nonStaticMethod() {
        System.out.println("Non-Static Method");
    }
}

Output:
MyClass.java:6: error: non-static variable nonStaticVar cannot be referenced from a static context
        System.out.println(nonStaticVar);
                           ^
MyClass.java:7: error: non-static method nonStaticMethod() cannot be referenced from a static context
        nonStaticMethod();
        ^
2 errors

Solution: To access non-static members within a static context, create an instance of the class to access these members.



Things to Consider

When working with the static keyword in Java, there are several important considerations to keep in mind:

  • Global State Management: Understand that static variables are shared across all instances. Be cautious about creating a global state, as it might lead to unexpected side effects and harder debugging.
  • Thread Safety Concerns: Static variables can pose challenges in multi-threaded environments. Consider synchronization or other thread-safe mechanisms when modifying shared static resources concurrently.
  • Class Loading Order: Static blocks are executed during class loading. Ensure that initialization within static blocks is appropriate and doesn’t cause unintended side effects during program startup.
  • Inheritance and Overriding: Static methods are not overridden in subclasses but can be re-declared, leading to method hiding. Understand the implications when using static methods in class hierarchies.
  • Testing and Mocking: Testing static methods or classes can be challenging. Consider dependency injection or mocking frameworks to facilitate the testing of code involving static elements.
  • Memory Management: Be aware that static variables persist for the entire lifespan of the application, potentially affecting memory usage. Avoid unnecessary static variables to prevent memory leaks.
  • Encapsulation and Modifiability: Maintain proper access control with static elements. Excessive use of static can reduce encapsulation, making the code less modifiable and harder to maintain.
  • Performance Impact: While static variables/methods can improve performance in certain scenarios, misuse or overuse might hinder performance due to increased memory consumption or contention.

FAQs

What is static in Java?

In Java, static is a keyword that signifies a member (variable, method, block, or class) belongs to the class itself rather than a specific instance of the class.

What does static mean in Java?

The static keyword denotes that a member is associated with the class and is shared among all instances. It’s not tied to a specific object but belongs to the class as a whole.

What is a static class in Java?

In Java, a static class is a nested class declared with the static keyword. It’s associated with the outer class but doesn’t require an instance of the outer class to be instantiated.

What is a static method in Java?

A static method in Java is a method associated with the class itself rather than with an instance. It can be called directly using the class name without creating an object of the class.

What is a static variable in Java?

A static variable in Java is a class-level variable that is shared among all instances of the class. There is only one copy of the static variable irrespective of the number of class instances.

Why can’t a static method refer to an instance variable?

Static methods are not tied to any specific instance and belong to the class itself. Instance variables belong to specific instances of the class, so static methods cannot directly access them.

How to call a static method in Java?

Static methods can be called using the class name followed by the method name, without needing to create an object of the class. For example: ClassName.methodName();.

What is the difference between static and final keywords in Java?

The static keyword is used to declare members that belong to the class and not to any specific object. The final keyword is used to declare members that cannot be changed or overridden. A member can be both static and final, which means it is a constant that belongs to the class.

What is the difference between static and non-static methods in Java?

A static method is a method that belongs to the class and not to any specific object. A non-static method is a method that belongs to an object and can access the state of the object. A static method can only access static members of the class, while a non-static method can access both static and instance members of the class.

What is the difference between static and non-static nested classes in Java?

Static Nested Classes: Associated with the outer class but instantiated independently and can’t directly access non-static outer class members.
Non-Static Nested Classes (Inner Classes): Tightly bound to outer class instances, accessing both static and non-static outer class members, and requiring an outer class instance for instantiation.

Can static methods access non-static (instance) variables or methods?

No, static methods cannot directly access non-static members of a class. They operate at the class level and do not have access to instance-specific data.

How does the usage of static affect memory management in Java?

Static variables persist for the entire duration of the program, potentially impacting memory usage. However, excessive use of static variables may lead to memory leaks if not managed properly.

Are static variables shared across different instances of a class?

Yes, static variables are shared among all instances of a class. Any modification to a static variable by one instance reflects across all other instances.

Can static methods be overridden in Java?

No, static methods belong to the class, not to individual instances, so they cannot be overridden in the same way as instance methods. Subclasses can re-declare static methods, leading to method hiding.

Why is the main method in Java declared as static?

The main method must be declared as static in Java to serve as the entry point of the program. This allows the JVM to invoke the method without creating an instance of the class.

Is it possible to access static variables without creating an object of the class?

Yes, static variables can be accessed using the class name itself without the need to instantiate the class.

How does static relate to thread safety in Java?

While static elements can be shared across threads, they can pose thread safety challenges if accessed and modified concurrently. Proper synchronization or thread-safe mechanisms might be necessary to ensure data integrity.

Conclusion

In summary, understanding the static keyword in Java is fundamental for effective programming. It helps share resources, create handy methods, and use memory efficiently. But if not used carefully, it might cause problems later. Knowing its strengths, limitations, and how to use it properly helps optimize Java code effectively.

Learn More

#

Interested in learning more?

Check out our blog on how to simplify declarations using Java var

Top Picks for Learning Java

Explore the recommended Java books tailored for learners at different levels, from beginners to advanced programmers.

Disclaimer: The products featured or recommended on this site are affiliated. If you purchase these products through the provided links, I may earn a commission at no additional cost to you.

1
Java: The Complete Reference
13th Edition

Java: The Complete Reference

  • All Levels Covered: Designed for novice, intermediate, and professional programmers alike
  • Accessible Source Code: Source code for all examples and projects are available for download
  • Clear Writing Style: Written in the clear, uncompromising style Herb Schildt is famous for
2
Head First Java: A Brain-Friendly Guide

Head First Java: A Brain-Friendly Guide

  • Engaging Learning: It uses a fun approach to teach Java and object-oriented programming.
  • Comprehensive Content: Covers Java's basics and advanced topics like lambdas and GUIs.
  • Interactive Learning: The book's visuals and engaging style make learning Java more enjoyable.
3
Modern Java in Action: Lambdas, streams, functional and reactive programming
2nd Edition

Modern Java in Action: Lambdas, streams, functional and reactive programming

  • Latest Java Features: Explores modern Java functionalities from version 8 and beyond, like streams, modules, and concurrency.
  • Real-world Applications: Demonstrates how to use these new features practically, enhancing understanding and coding skills.
  • Developer-Friendly: Tailored for Java developers already familiar with core Java, making it accessible for advancing their expertise.
4
Java For Dummies
8th Edition

Java For Dummies

  • Java Essentials: Learn fundamental Java programming through easy tutorials and practical tips in the latest edition of the For Dummies series.
  • Programming Basics: Gain control over program flow, master classes, objects, and methods, and explore functional programming features.
  • Updated Coverage: Covers Java 17, the latest long-term support release, including the new 'switch' statement syntax, making it perfect for beginners or those wanting to brush up their skills.

Add a Comment

Your email address will not be published.