Back to Java
2026-02-285 min read

Java Static Keyword

Learn Java Static Keyword step by step with clear examples and exercises.

Why This Matters

Java is a popular programming language that emphasizes object-oriented programming (OOP). One of the essential features in Java is the static keyword, which provides a way to create class variables and methods that belong to the class itself rather than individual objects. This lesson will delve into the use cases, syntax, and best practices for the static keyword in Java.

Why This Matters

The static keyword plays a crucial role in Java programming, especially when dealing with classes and their members. Understanding its usage can help you write more efficient code, avoid common mistakes, and create well-structured programs. In interviews, interviewers often test your understanding of the static keyword to gauge your proficiency in Java. Additionally, real-world applications frequently use the static keyword to manage shared resources or utility classes.

Prerequisites

To fully grasp the concepts presented in this lesson, it is essential to have a solid foundation in Java programming basics:

  1. Understanding of basic data types and operators
  2. Familiarity with control structures (if-else, loops)
  3. Knowledge of classes and objects
  4. Basic understanding of inheritance and polymorphism

Core Concept

Class Variables

Class variables, also known as static variables, are declared using the static keyword and belong to the class rather than individual objects. They are shared among all instances of a class and retain their values even when no objects exist. To declare a class variable, use the following syntax:

private static <type> <variableName>;

Example:

public class Counter {
private static int count = 0;
}

In this example, count is a class variable that starts with a value of 0 and can be accessed by any method within the Counter class.

Methods

Similarly, you can declare methods as static, meaning they do not require an instance of the class to be called. Instead, they are called using the class name directly. To declare a static method, use the following syntax:

public static <returnType> <methodName>(<parameters>) {
// Method body
}

Example:

public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}

In this example, the add method is a static method that can be called using the class name (i.e., MathUtils.add(5, 3)) without creating an instance of the MathUtils class.

Accessing Class Variables and Methods

To access a class variable or method, use either an instance of the class or the class name directly:

  • Using an instance:
Counter counter = new Counter();
counter.count++; // Increment the count for this specific object
System.out.println(counter.count); // Print the count for this specific object
  • Using the class name directly:
Counter.count++; // Increment the count for the class as a whole
System.out.println(Counter.count); // Print the count for the entire class

Static Blocks

A static block is a special type of block that gets executed when the class is loaded by the JVM. This can be useful for initializing class variables or performing some setup tasks before any objects are created. To create a static block, place it immediately after the class declaration and enclose it in curly braces:

public class MyClass {
static {
// Code to execute when the class is loaded
}
}

Worked Example

Let's create a simple Counter class that uses the static keyword to keep track of the total number of instances created.

public class Counter {
private static int instanceCount = 0;

private Counter() {
instanceCount++;
}

public static Counter getInstance() {
return new Counter();
}

public void displayInstanceCount() {
System.out.println("Total instances: " + instanceCount);
}
}

Now, let's create multiple instances of the Counter class and demonstrate how to access the static variable and method:

public class Main {
public static void main(String[] args) {
Counter counter1 = Counter.getInstance();
Counter counter2 = Counter.getInstance();
Counter counter3 = Counter.getInstance();

counter1.displayInstanceCount(); // Output: Total instances: 3
}
}

Common Mistakes

  1. Forgetting the static keyword when declaring a class variable or method: This will result in a compile-time error, as the variable or method will be associated with an object instead of the class.
  2. Accessing a non-static class variable or method using the class name directly: This will result in a compile-time error, as the JVM cannot determine which object's instance variable or method is being referenced.
  3. Trying to call a static method on an instance of the class: This will result in a compile-time error, as static methods are not associated with individual objects.
  4. Not initializing a static variable before using it: If a static variable is not initialized before being used, it will retain its default value (0 for numeric types and null for object types).
  5. Using static variables or methods inappropriately: Overuse of the static keyword can lead to code that is difficult to maintain and understand, as it may hide dependencies between objects and violate encapsulation principles.

Practice Questions

  1. Write a Logger class with static methods for logging messages at different levels (e.g., INFO, WARNING, ERROR).
  2. Create a utility class called MathOperations that contains static methods for performing common mathematical operations such as addition, subtraction, multiplication, and division.
  3. Write a Shape class with static variables to store the total area and perimeter of all shapes created, and static methods to calculate the area and perimeter of specific shapes (e.g., Circle, Rectangle).
  4. Implement a Singleton pattern using the static keyword in Java.

FAQ

  1. Why can't I access non-static variables or methods from a static context?

Non-static members are associated with individual objects, while static members belong to the class as a whole. Therefore, they cannot be accessed directly within a static context without an instance of the class.

  1. Can I override static methods in Java?

No, static methods are not part of an object's state and do not participate in inheritance hierarchies, so they cannot be overridden.

  1. What happens when multiple threads access a shared static variable simultaneously?

Accessing a shared static variable concurrently can lead to race conditions and inconsistent results. To avoid this, consider using synchronized blocks or atomic variables.

  1. Why is it important to use the static keyword judiciously in Java?

Overuse of the static keyword can make code more difficult to maintain and understand, as it may hide dependencies between objects and violate encapsulation principles. It's essential to balance its usage with proper object-oriented design principles.

Java Static Keyword | Java | XQA Learn