Static Keyword in Java

static-keyword-in-java.jpg

Static in Java is one of those keywords that you bump into early in your Java development journey and then keep seeing everywhere. The static keyword in Java lets you attach variables or methods directly to a class, not to the object that you create from it. This way, you don’t have to make an object just to call main() or grab a constant.

Sounds convenient, right? It is, but it’s also one of the easiest things to misuse if you don’t have an in-depth understanding of how it works.

Today, we’ll break down what static in Java really means and how it works behind the scenes. Let’s get started.

Table of Contents:

What is a static Keyword in Java?

In Java, the static keyword means “belonging to the class, not the object.” It can be used with variables, methods, blocks, and even inner classes.

Usually, when you create an object from a class, each object gets its own copy of the variables and methods. But when something is marked as static, there’s only one copy shared across all objects.

Characteristics of static in Java

Before we jump deep into the meaning of static in Java and how it works with variables, methods, and blocks, let’s first look at some of the characteristics of the static keyword that separate static and non-static code in Java. The keyword might seem small, but the change in behaviour that it causes is anything but minor.

So what is it that makes something static?

1. Belongs to the Class, Not the Object

This is at the core of static in Java. When you mark a variable or method as static, it no longer belongs to the individual object and rather becomes part of the class itself. This means that regardless of the number of objects you make, there will only be one shared copy of the variable or method that is marked static.

In contrast, non-static (or instance) variables are duplicated for every new object. Each object gets its own private version.

2. Memory Efficiency

Another reason why the static keyword is so popular among developers is that static members are stored in the Method Area (in JVM). This drastically reduces memory usage, especially when you need to use the same value or logic repeatedly across multiple instances.

3. Accessible Without Creating an Object

This is one of the first things people notice. You don’t need to create an instance just to use a static method or variable. You simply refer to it using the class name:

MyClass.myStaticMethod();

4. Runs When the Class Loads

Static blocks and static variables are initialized the moment the class is loaded into memory. This happens before any constructor runs, and even before main() gets a chance. That makes static blocks perfect for one-time setup code.

Put all of these traits together, and you’ve got a tool that’s ideal for constants, utility methods, and anything that should be initialized only once. Of course, it’s not all upside; there are trade-offs too, which we’ll get into as we move forward.

Static Variables in Java (Class Variables)

Java static variables are probably the first use case that you will run into while working with the static keyword. They are one of the cleanest examples of how the static keyword changes the way data behaves.

Let’s say you want a variable that’s shared by all instances of a class, not copied for each one. That’s exactly what static variables in Java are made for.

What Are Static Variables?

A static variable belongs to the class itself and not any particular object. This means that regardless of the number of instances that you create, it will still point to the same shared variable in memory.

Here is the basic syntax:

class Example {
    static int count = 0; // static variable
}

This count variable is created once when the class loads, and that’s it. No matter how many objects you make, they’ll all refer to the same count.

Real-World Example

Let’s say that you want to keep track of how many objects of a class have been created. A static variable is perfect for this.

Java

Output:

static variable

As you can see, no matter how many Counter objects are created, they’ll refer to the same count variable.

When to Use Static Variables in Java

Java Static variables make sense when you want a single value to be consistent across every object. Some scenarios where static variables are useful are:

  • Counters and global flags
  • Configuration values
  • Constants (especially when combined with final)

Just remember, because static variables are shared, they can also introduce shared side effects. Use them carefully in multi-threaded environments or when dealing with user-specific data.

Static Methods in Java

Another way to use the static keyword is in static methods. You have probably already seen the Java main() method. This is a static method, and we will cover the why in a later section.

What Is a Static Method?

A static method in Java is a method that belongs to the class itself and not an object of said class. You can use it without creating an instance of that class by calling it directly using the class name.

Static methods are perfect for declaring behaviour that does not rely on object-specific data.

Here’s how you declare one:

class Utility {
    static void sayHello(String name) {
        System.out.println("Hello, " + name);
    }
}

You can easily call it like so: 
Utility.sayHello(“Java”);

Real-World Example

Imagine that you are building a calculator. You would not need to store any data, only perform basic mathematical operations, right? A static method is the perfect choice here.

Java

Output:

mathematical operations

Static Blocks in Java

In Java, the code inside a class is usually run when an instance of the class is created. This is where static blocks in Java come in. It lets you run a chunk of code once when the class is loaded.

What Is a Static Block?

Simply put, a static block in Java is a block of code that is marked with the static keyword. It will only run once at the moment when the class is loaded into memory by the JVM.

class Config {
    static {
        // one-time setup
        System.out.println("Static block executed.");
    }
}

The moment the Config class is loaded, this message will print regardless of whether an object is ever created.

Real-World Example

Let’s say, for example, that you want to load a database driver when our program starts. A static block is the perfect place to do this.

Java

Output:

database driver

When the DatabaseConnector class is loaded, the driver gets set up right away. No need for a constructor or method call.

When to Use Static Blocks

  • Setting up static variables with logic more complex than a simple assignment
  • Running one-time setup tasks like logging or configuration
  • Loading external resources or dependencies early in the application’s lifecycle

Static blocks in Java are a great tool for initializing shared resources before any instance or method gets involved.

Static Nested Classes

In Java, you can define a class within another class. If you mark one of these as static, you get a static nested class. It behaves a bit differently from a regular inner class. Let’s find out how.

What Is a Static Nested Class?

In Java, a static nested class is an inner class that is static. This means that a static class is defined in another class. Simply put, it does not rely on an object of the outer class to exist. Here is a simple syntax:

class OuterClass {
    // Static nested class
    static class NestedClass {
      // Methods or fields
      void display() {
         System.out.println("Inside static nested class.");
      }
    }
    public static void main(String[] args) {
      // Creating object of static nested class
      OuterClass.NestedClass obj = new OuterClass.NestedClass();
      obj.display();
    } 
}

Real-world Example

Here’s a basic example:

Java

Output:

Static Nested Class
  • Outer is the outer class, it’s also the entry point of your program since it contains the main() method.
  • Inside Outer, we define a static nested class called Inner. Because it’s static, it doesn’t need an instance of Outer to be created.
  • In the main() method, we directly create an instance of Inner using new Inner().
  • Once we have the Inner object, we call its showMessage() method, which simply prints a line of text to the console.

Normally, with a non-static inner class, you’d need an object of the outer class to access it. But since Inner is declared static, it behaves like a top-level class in terms of instantiation

When Should You Use Static Nested Classes?

A static nested class in Java makes sense when:

  • The nested class doesn’t need to touch instance data from the outer class
  • It’s mainly there to support or extend the outer class in some logical way
  • You want clean, organized code without adding too much clutter

Real-World Examples of Java Static

Now that we understand what static means in Java and how it behaves in Java, let’s look at how it’s actually used in real programs. 

1. Static Utility Method: Celsius to Fahrenheit Converter

Let’s say that you are working on a weather app and you need to convert temperatures between Celsius and Fahrenheit frequently. Remember, we are not storing data, just performing a quick arithmetic calculation.

Java

Output:

Static Utility Method

Try changing the values to see the magic happen for yourself.

2. Constants with static final: Quiz App Settings

Imagine that you want to declare values that never change and make them available to throughout the program. 

Java

Output:

Constants with static final

Declaring variables as static final creates constants that belong to the class and never change. This approach improves readability and avoids accidental updates to fixed values.

3. Shared Static Variable: Login Counter

If you want to track how many users have logged in, you can use the static method like so:

Java

Output:

Shared Static Variable

totalLogins is a shared variable. Every time recordLogin() is called, it updates the same counter. This is a great way to maintain a global state without creating unnecessary objects.

4. Static Block: One-Time Setup Code

When you want to initialize something important, like a configuration setting, when your class loads, relying on a method call can be very ineffective. 

Java

Output:

Static Block

The static block runs once when the class is loaded. This makes it ideal for loading resources, setting defaults, or initializing static variables with logic (instead of hardcoding values).

5. Static Nested Class: Currency Converter

If you have a helper class that doesn’t need access to the outer class’s instance data. To keep it organized, you nest it and mark it static.

Java

Output:

Currency Converter

Common Errors in Java Static

Like many of the keywords in Java, static, too, can be incredibly useful. But if you do not have a solid understanding of how it works, it is easy to mess up the implementation as well.

Let’s walk through some common mistakes that beginner Java developers make and how to avoid them.

1. Accessing Non-Static Members from a Static Context

Let’s start with the error most beginners bump into first:

class Demo {
    int x = 5;
    static void printX() {
        System.out.println(x); //  Error: non-static variable x cannot be referenced
    }
}

Why it fails:

The printX() method is static and therefore does not operate on a specific object. But x here is an instance variable, and without an object, there is no x to refer to.

Fix:

Either make x static too, or access it through an object:

Demo d = new Demo();
System.out.println(d.x);

2. Overusing Static

Sure, you can make lots of things static, but should you? Not always, overusing static is a common beginner mistake that can:

Use the static keyword in Java only when it makes sense, like for constants, counters, or shared utility functions.

3. Confusion Around Static and Object Lifecycles

Many beginners assume that static variables go away when objects do. Not true.

class Counter {
    static int count = 0;
    Counter() {
        count++;
    }
}

Even if you nullify or lose references to Counter objects, the static variable count stays in memory until the class is unloaded (typically when the app shuts down or it is garbage collected).

4. Using this or super in Static Methods

Although it may seem like a small detail, this is a common mistake that beginner Java programmers tend to make. Static methods cannot use this or super.

class Test {
    static void show() {
        System.out.println(this); // Error
    }
}

Why? Because there’s no this in a static method. It doesn’t operate on a specific object.

Static vs Non-static in Java

One of the most common questions Java beginners ask is: “When should I use Java static, and when should I stick to regular (non-static) members?” It’s a great question, and the answer boils down to how you want your code to behave. Let’s compare.

FeatureStaticNon-static
Belongs toThe class itselfA specific object (instance)
Accessed viaClass name (or object, but not required)Only through an object
Memory allocationAllocated once when the class is loadedNew memory per object
Can access instance data?NoYes, can use instance-specific data
Can be used in main()?YesNo
Use caseShared tools, constants, countersPer-object logic, overridden methods

When to Use Which

Use static when:

  • You want to share a value or method across all instances
  • You’re writing utility functions (e.g., Math.pow())
  • You’re defining constants (static final)

Use non-static when:

  • Each object should maintain its own state (like name, age)
  • You want to override behavior in subclasses
  • You rely on this or instance-specific logic

Conclusion

The static keyword in Java may seem simple at first glance, but as we’ve seen, it plays a powerful role in shaping how your classes behave. Whether you’re working with utility methods, shared counters, constants, or nested classes, understanding how static works can make your code cleaner, faster, and easier to manage.

Keep in mind that this is merely one piece of the bigger Java puzzle. If you want to dig deeper into how Java works and gain experience through real-world projects, consider checking out our Java Certification Course. It has been designed to cater to the complete beginner and will take you from the bare basics to advanced topics.

Static Keyword in Java – FAQs

Q1. Can we override static methods in Java?

Not exactly. You can’t override a static method in the same way you override an instance method. Why? Because static methods belong to the class, not the object. When the compiler sees a static method, it locks in the version to use at compile time. That means there’s no runtime polymorphism happening here.
You can define a static method with the same name in a subclass, but that’s called method hiding, not overriding. It might look similar at a glance, but it behaves differently under the hood.

Q2. Why is the main() method static in Java?

When your program starts, there are no objects yet, just your class. The Java Virtual Machine (JVM) needs a way to kick things off without creating an object first.
That’s the reason main() has to be static, so the JVM can jump in without needing an object.

public static void main(String[] args) {
    // Entry point of every Java program
}

This method gets called before anything else. No object, no problem.

Q3. Can Java static methods access non-static variables?

No. Static methods don’t have access to instance variables or methods directly because they’re not tied to any object.
But if you really need to access a non-static variable, you can do it through an object:

MyClass obj = new MyClass();
System.out.println(obj.instanceVar);
Q4. Can we make a constructor static?

No, Java doesn’t allow that. Constructors are tied to object creation, and static belongs to the class, not to an object. So, it’s kind of a contradiction.
But if you want something similar, you can use a static factory method. It gives you control over how objects are created.

public static MyClass create() {
    return new MyClass();
}

This is a popular design pattern in frameworks and libraries where custom creation logic is needed.

Q5. What happens if I declare a variable static and final?

When you combine static and final, you’re creating a constant. It’s shared across the class (thanks to static), and its value can’t be changed (thanks to final).

public static final int MAX_USERS = 100;

static ensures the variable is shared, and final makes it immutable. This combo is perfect for config values, limits, fixed strings, and other constants that should stay the same throughout the application.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner