Question

When to Use Static Methods in Java

javastatic-methods

Question

I am trying to understand when to use static methods in Java.

Suppose I have a class with a few getters and setters, plus one or two other methods. I want those methods to be callable only on an instance of the class.

Does that mean those methods should be static, or not?

For example:

Obj x = new Obj();
x.someMethod();

Or should it be written like this?

Obj.someMethod();

Is the second form what makes a method static? I am confused about when a method should belong to the class itself versus an object created from that class.

Short Answer

By the end of this page, you will understand the difference between instance methods and static methods in Java, when each should be used, how method calls like obj.method() and Class.method() differ, and the common rules developers follow in real code.

Concept

In Java, a method can belong to either:

  • an instance of a class, or
  • the class itself.

An instance method works with a specific object. You call it on an object:

Obj x = new Obj();
x.someMethod();

A static method belongs to the class, not to any one object. You call it on the class name:

Obj.someMethod();

The key question is this:

Does the method need data from a specific object?

  • If yes, make it an instance method.
  • If no, and it performs work that does not depend on object state, it can be a static method.

Why this matters

This distinction is important because it affects how your program is designed.

  • Instance methods model behavior of real objects.
  • Static methods model behavior that is shared, global, or independent of any object.

Example

public class BankAccount {
    private double balance;

    public void deposit(double amount) {
        balance += amount;
    }

    public double getBalance() {
        return balance;
    }
}

Here, deposit() and getBalance() should not be static, because they depend on a specific account's balance.

By contrast:

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

add() does not depend on any object fields, so making it static makes sense.

Important rule

Getters and setters are almost always instance methods, because they read or change the fields of a specific object.

user.getName();
user.setName("Sam");

These should not usually be static, because each object can have different values.

Mental Model

Think of a class as a blueprint for houses, and an object as one actual house built from that blueprint.

  • An instance method is something you do with one specific house, like paintWall() or openDoor().
  • A static method is something related to the blueprint itself, or a general utility, like calculateBuildingCost().

Another way to think about it:

  • Instance method = needs a specific object
  • Static method = does not need a specific object

So if a method needs to know the values inside x, call it like this:

x.someMethod();

If it does not care about any particular object, it may be static:

Obj.someMethod();
Take Quiz

Syntax and Examples

Instance method syntax

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Usage:

Person p = new Person("Ava");
System.out.println(p.getName());

getName() is an instance method because it returns data from a particular Person object.

Static method syntax

public class StringUtils {
    public static boolean isEmpty(String value) {
        return value == null || value.isEmpty();
    }
}

Usage:

boolean result = StringUtils.isEmpty("");
System.out.println(result);

isEmpty() is static because it does not depend on fields stored in a StringUtils object.

Side-by-side example

public class Counter {
    private int count;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }

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

Usage:

Counter c = new Counter();
c.increment();
System.out.println(c.getCount()); // 1

System.out.println(Counter.add(2, 3)); // 5

Explanation:

  • increment() changes one specific Counter object.
  • getCount() reads one specific Counter object's state.
  • add() just combines two numbers and does not use object state, so it can be static.

Step by Step Execution

Consider this code:

public class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public static void sayHello() {
        System.out.println("Hello");
    }
}

public class Main {
    public static void main(String[] args) {
        Counter c = new Counter();
        c.increment();
        Counter.sayHello();
    }
}

Step by step

  1. Counter c = new Counter();

    • A new Counter object is created.
    • Its count field starts at 0.
  2. c.increment();

    • Java looks at the specific object stored in c.
    • The increment() method runs on that object.
    • count becomes 1.
  3. Counter.sayHello();

    • Java calls sayHello() on the class itself.
    • No object is needed.
    • The method prints Hello.

Key observation

Inside a static method, there is no current object reference like this.

That means this is invalid:

public static void badMethod() {
    count++; // error
}

Why? Because count belongs to an object, but badMethod() is not running on any particular object.

Real World Use Cases

Static methods are useful when behavior does not belong to one specific object.

Common uses for static methods

Utility/helper methods

Integer.parseInt("42");
Math.max(5, 9);

These methods perform work without needing an instance.

Factory methods

Sometimes a class provides a static method to create objects:

LocalDate today = LocalDate.now();

now() is static because it creates or returns a value without needing an existing LocalDate object.

Shared constants or class-level behavior

A method may work with data shared by the whole class rather than one object.

Common uses for instance methods

Working with object state

cart.addItem(product);
user.changePassword("newPass");
account.withdraw(100);

These actions affect one particular object.

Getters and setters

user.getEmail();
user.setEmail("a@example.com");

These usually belong to an instance because each object has its own values.

Domain behavior

In real applications, methods that represent what an object can do are usually instance methods.

order.cancel();
invoice.calculateTotal();
player.move();
Take Quiz

Real Codebase Usage

In real Java codebases, developers usually choose between static and instance methods based on whether the method depends on object state.

Typical patterns

1. Instance methods for domain objects

Classes like User, Order, Cart, and BankAccount usually have instance methods because each object has its own data.

order.calculateTotal();
user.getDisplayName();
cart.clear();

2. Static methods for stateless helpers

Utility classes often contain only static methods.

public class PriceUtils {
    public static double applyDiscount(double price, double percent) {
        return price - (price * percent / 100.0);
    }
}

3. Static factory methods

Instead of using constructors directly, a class may offer named static methods:

public class User {
    private String name;

    private User(String name) {
        this.name = name;
    }

    public static User createGuest() {
        return new User("Guest");
    }
}

This can make code more readable.

4. Validation helpers

Validation logic that does not need instance state is often static.

public class Validation {
    public static boolean isValidEmail(String email) {
        return email != null && email.contains("@");
    }
}

5. Avoid overusing static methods

If everything becomes static, code can become harder to test, extend, and model properly. If behavior belongs to a real object, instance methods usually lead to better object-oriented design.

Common Mistakes

1. Making a method static just because you want to call it easily

Beginners sometimes make methods static to avoid creating an object.

Broken design:

public class User {
    private String name;

    public static String getName() {
        return name; // error
    }
}

Problem:

  • name belongs to each User object.
  • A static method has no specific User object to read from.

Fix:

public class User {
    private String name;

    public String getName() {
        return name;
    }
}

2. Trying to access instance fields from a static method

Broken code:

public class Example {
    private int value = 10;

    public static void printValue() {
        System.out.println(value); // error
    }
}

Fix options:

  • Make the method an instance method, or
  • Pass an object into the static method

Example:

public class Example {
    private int value = 10;

    public void printValue() {
        System.out.println(value);
    }
}

3. Calling an instance method as if it were static

Broken code:

public class Dog {
    public void bark() {
        System.out.println("Woof");
    }
}

Dog.bark(); // error

Fix:

Dog d = new Dog();
d.bark();

4. Making getters and setters static

Usually this is wrong unless the field itself is static.

Broken idea:

public class Product {
    private String name;

    public static void setName(String name) {
        this.name = name; // error
    }
}

Why it fails:

  • this is only available in instance methods.
  • name belongs to each product object.

5. Confusing static with "private" or "restricted"

static does not mean:

  • only callable from inside the class
  • more secure
  • tied to one object

It only means the method belongs to the class rather than an instance.

Comparisons

ConceptInstance MethodStatic Method
Belongs toAn objectThe class
Called withobj.method()ClassName.method()
Can access instance fields directlyYesNo
Can use thisYesNo
Needs object creation firstUsually yesNo
Common useObject behavior, getters, settersUtilities, helpers, factories

Static method vs instance method

public class Example {
    private int value;

    public void setValue(int value) {
        this.value = value;
    }

    public static int doubleNumber(int x) {
        return x * 2;
    }
}
  • setValue() changes one object's state.
  • doubleNumber() just computes a result.

Static field vs static method

A static field is shared by all objects of the class. A static method belongs to the class.

Example:

public class VisitorCounter {
    public static int totalVisitors = 0;

    public static void addVisitor() {
        totalVisitors++;
    }
}

Both are class-level members.

Take Quiz

Cheat Sheet

// Instance method
class User {
    private String name;

    public String getName() {
        return name;
    }
}

User u = new User();
u.getName();

// Static method
class MathHelper {
    public static int square(int x) {
        return x * x;
    }
}

MathHelper.square(4);

Quick rules

  • Use an instance method if the method needs object data.
  • Use a static method if the method does not depend on object data.
  • Getters and setters are usually instance methods.
  • Static methods are called with ClassName.method().
  • Instance methods are called with object.method().
  • Static methods cannot directly use:
    • instance fields
    • instance methods
    • this

Easy test

Ask:

Does this method need to know anything about one specific object's state?

  • If yes → instance method
  • If no → static method

Common examples

  • Instance: user.getName()
  • Instance: account.deposit(50)
  • Static: Math.max(1, 2)
  • Static: Integer.parseInt("42")

FAQ

Should getters and setters be static in Java?

Usually no. Getters and setters normally work with fields stored in a specific object, so they should be instance methods.

When should I make a method static?

Make a method static when it does not depend on instance fields or instance behavior. Utility and helper methods are common examples.

Can a static method access instance variables?

Not directly. A static method does not run on a specific object, so it cannot directly use instance variables.

Can an instance method call a static method?

Yes. Instance methods can call static methods in the same class directly, or through the class name.

Can a static method create objects?

Yes. Static methods often create and return objects, such as factory methods.

Is ClassName.method() always static?

Yes, that syntax is used for static methods. If a method is not static, you should call it on an object.

Are static methods object-oriented?

They can be useful in object-oriented programs, but they are not tied to object state. If behavior belongs to an object, instance methods are usually a better fit.

Take Quiz

Mini Project

Description

Build a small Java program with a Rectangle class to practice the difference between instance methods and static methods. The rectangle should store its own width and height, while a separate static utility method performs a calculation that does not belong to one specific rectangle.

Goal

Create a program where instance methods work with one rectangle's data, and a static method performs a general calculation that can be called on the class.

Requirements

  • Create a Rectangle class with width and height fields.
  • Add instance methods to calculate area and perimeter.
  • Add a static method that converts centimeters to inches.
  • In main, create a rectangle object and call both the instance methods and the static method.
  • Print the results clearly.
Take Quiz

Keep learning

Related questions

View more