Calling Class Methods

Class Methods (Static Methods)

A method marked static belongs to the class itself, not to any object — called a class method or static method. main is static too: in this course it's always public static void main(String[] args). Call a static method using the class name and the dot operator:

double distance = Math.abs(target - current);

Inside the same class that defines the method, you can drop the class name and just call it directly.

Java 25 note: Java 25 also accepts a shorter, non-static void main() as a program's entry point. On Java 17, main must be public static void main(String[] args) — which works on every version, so it's what this course uses.

Void vs. Non-Void Methods

A void method doesn't return anything — you call it purely for its effect (like printing, or setting a motor's speed). A non-void method computes and returns a value, which the caller should actually use:

public static int square(int number)
{
    int result = number * number;
    return result;
}

return sends the value back to whoever called the method, and ends the method immediately — nothing after return runs.

int y = square(5);        // stored in a variable
System.out.println(square(4)); // used directly in an expression

Common Errors

  • Forgetting to do something with a non-void method's return value — it should be stored or used; Java lets you ignore it, but then the call's result is wasted.
  • A type mismatch between what a method returns and what you try to store it in (assigning a double return into an int variable won't compile).
  • Wrong argument count or type at the call site (or two arguments swapped — see Lesson 4.1).
int total = calculateChecksum(data); // fine — assuming calculateChecksum returns an int
// compiles, but the returned value is silently thrown away:
calculateChecksum(data);

Common Pitfalls

  • Calling a non-void method and doing nothing with the result. It still compiles — Java doesn't force you to use a return value, which makes this an easy mistake to miss.
  • Assigning a return value to the wrong type. A double-returning method's result can't go straight into an int variable without an explicit cast (Ch.2.4) — and casting one truncates the decimal, which may not be what you wanted.

Key Takeaways

  • A static method is a class method, called via the class name (or bare, from inside the same class).
  • A void method returns nothing; a non-void method computes a value that should be stored or used.
  • return sends a value back to the caller and ends the method immediately.
  • A non-void method's return value being ignored is a real, easy-to-miss bug — it still compiles.

Derived from csawesome-2026: unit-1-using-objects-and-methods/1.10-calling-class-methods.md (CSA 1.10)