Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 201 ยท Methods

Static vs Instance Methods

Learn the difference between static and instance methods in Java, the calling rules, the "non-static method cannot be referenced" error, utility classes and how to choose.

So far, most methods in this course have been called on their own: square(5), max(3, 9). Others are called on something: name.length(), list.add("x"), word.toUpperCase(). That difference is not just syntax. It's the difference between static methods, which belong to a class as a whole, and instance methods, which belong to an individual object and work with that object's data.

Understanding the split is the bridge from writing methods to writing classes. It explains the famous compiler error "non-static method cannot be referenced from a static context", why Math.sqrt needs no object but "hello".length() does, and how to decide which kind each new method should be. You'll get a first, gentle look at objects here; the next chapter, starting with Object-Oriented Programming, builds on it.

Two kinds of methods, side by side

A static method is marked with the static keyword. It belongs to the class. You call it with the class name: Math.max(3, 9), Integer.parseInt("42"). It has no "current object", so it works only with its parameters (and static fields).

An instance method has no static keyword. It belongs to each object made from the class. You call it on an object: account.deposit(50). Inside, it can read and change that object's fields, because it always knows which object it was called on.

Java A class with both kinds of method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

report() and warmBy() need a particular thermometer: "report which thermometer?" toFahrenheit doesn't: converting 30 degrees gives the same answer no matter which thermometer you ask, so it doesn't belong to any one of them. The lines with Thermometer(...) and this.place are a constructor, which sets up a new object; you'll study it in Constructors.

The calling rules

The rules follow from one fact: an instance method always runs for some object, and a static method doesn't.

From inside... Call a static method Call an instance method Use instance fields
a static method Yes, directly: toFahrenheit(5) Only through an object: kitchen.report() Only through an object: kitchen.celsius
an instance method Yes, directly Yes, directly (on the same object) Yes, directly (or as this.field)

From outside the class you write ClassName.staticMethod() for static methods and someObject.instanceMethod() for instance methods.

"non-static method cannot be referenced from a static context"

This is one of the most searched Java errors. It appears when a static method, usually main, tries to call an instance method directly. The example below fails to compile on purpose:

Java The classic static-context error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

javac reports both lines: non-static method click() cannot be referenced from a static context and non-static variable clicks cannot be referenced from a static context. The compiler is asking a fair question: click() updates some object's clicks, but main is static, so there is no object. There are two fixes, and choosing between them is the real skill:

  1. Create an object and call the method on it, when the data really belongs to an object.
  2. Make the method static, when it doesn't use any instance data at all.
Java Both fixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Don't fix the error by making everything static, which beginners often do. It compiles, but all data then becomes shared by the whole program: there would be just one clicks instead of one per counter. That's exactly the bug objects exist to prevent.

Compact source files are instance-based

The compact void main() files used in earlier lessons hide a detail: everything in them belongs to an implicit class, and main is an instance method of that class (see The main Method and Command-Line Arguments). The launcher creates one object of it and calls main on that object.

That's why helper methods and fields in compact files work without static: main and the helpers are all instance members of the same object.

Java Instance members in a compact file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

If you add static to main in that file (static void main()), the call greet("Ana") fails with the same static-context error, for the same reason. In a classic public class Main with public static void main, helper methods that main calls directly must be static, which is why traditional examples put static on everything.

When should a method be static?

Ask one question: does this method need the data of a particular object?

Make it static when:

  • it computes its result purely from its parameters: Math.abs(x), Integer.parseInt(s), celsiusToFahrenheit(c);
  • it creates objects for you (a static factory): List.of(...), LocalDate.of(2025, 3, 14), Path.of("a", "b");
  • it works on objects it receives rather than on this: Collections.sort(list), Arrays.fill(array, 0);
  • it's the entry point public static void main(String[] args).

Make it an instance method when:

  • it reads or changes the object's state: account.deposit(100), list.add(x);
  • the result depends on which object you ask: name.length(), date.getDayOfWeek();
  • different kinds of objects should be able to respond differently (overriding, which only works for instance methods; see Polymorphism and Method Overriding).

When in doubt, start with an instance method on the class whose data it uses. A good smell test: if a static method takes an object as its first parameter and only pokes at that object's fields, it probably wants to be an instance method of that object's class.

Utility classes

A class that contains only static methods is a utility class. The JDK has many: Math, Arrays, Collections, Objects, Files. Utility classes are usually final and have a private constructor so that nobody creates pointless objects of them:

Java Writing a small utility class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Utility classes are fine for pure helpers. If you find yourself writing AccountUtils.deposit(account, 100), though, the method belongs on Account.

Things that surprise people

Calling a static method through a reference is legal but misleading. If t is a Thermometer, then t.toFahrenheit(5) compiles, but Java ignores t entirely and calls Thermometer.toFahrenheit(5). It even works when t is null! IDEs warn about this; always use the class name for static calls so readers aren't fooled.

Java
Thermometer t = null;
System.out.println(t.toFahrenheit(100));   // prints 212.0: t is never used!

Static methods can't use this. There is no current object, so this doesn't exist inside a static method. Writing this.place there is a compile error.

Static methods aren't overridden. A subclass can declare a static method with the same signature, but that hides the parent's method rather than overriding it, and the version called depends on the declared type, not the actual object. You'll see the difference in Polymorphism and Method Overriding.

Static state is shared, and that has costs. Static fields (covered in Static Fields, Methods and Blocks) exist once for the whole program. Static methods that change static fields behave like global variables: convenient, but harder to test and dangerous with multiple threads. Static methods that use only their parameters have none of these problems, which is why pure static helpers are so common.

Performance is not a reason to choose static. The JIT compiler makes both kinds of calls fast, and the difference is negligible in real programs. Choose based on whether the method needs an object's data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a classic public class Main, public static void main calls printReport(), declared as void printReport() { ... }. What happens?

    A static method has no current object, so it can't call an instance method directly. Either create an object (new Main().printReport()) or make printReport static.
  2. 2. Which method is the best candidate to be static?

    gcd depends only on its arguments and needs no object's data. The others read or change the state of a particular account, person or cart.
  3. 3. Given static int twice(int n) in class Calc, and Calc c = null;, what does c.twice(4) do?

    A static method call through a reference is compiled as Calc.twice(4); the reference is not used, so null doesn't matter. It's legal but misleading, so always use the class name.
  4. 4. Two objects a and b of class Counter each call the instance method increment() once, which does count++ on an instance field. What are a.count and b.count?

    Each object has its own copy of an instance field, and an instance method changes the fields of the object it was called on.
  5. 5. In a compact source file, why can void main() call void helper() without any object or static keyword?

    Members of a compact file belong to an implicit class. Its main is an instance method, so it can call other instance methods directly on the same object.

Summary

  • Static methods belong to the class and are called as ClassName.method(); they have no current object and no this.
  • Instance methods belong to objects, are called as object.method(), and can use that object's fields directly.
  • Static methods can call instance methods only through an object; instance methods can call both kinds directly.
  • "non-static ... cannot be referenced from a static context" means a static method tried to use instance members; fix it by creating an object or, if no instance data is used, making the method static.
  • Make a method static when it depends only on its parameters (helpers, factories); otherwise prefer an instance method on the class that owns the data.
  • Utility classes hold only static methods and have a private constructor; in compact files, main and helpers are instance members of an implicit class.

Next: Object-Oriented Programming, where you'll see why Java organizes programs around objects, and what that buys you.