Methods: Reuse Logic with Structure

Introduction

A method is a named block of code that performs a task. You have been using main since Hello World; this chapter generalizes methods: parameters, return values, overloading, and static methods. A light class example appears here; full class design is in Classes.

Prerequisites

What Is a Method

Methods group logic you can call repeatedly.

java
public class MethodDemo {
 
    // Instance method (needs an object to call — see Classes chapter)
    void greet() {
        System.out.println("Hello!");
    }
 
    public static void main(String[] args) {
        greetStatic();
    }
 
    static void greetStatic() {
        System.out.println("Hello from static method!");
    }
}

Structure:

java
modifiers returnType methodName(parameterList) {
    // body
    return value;  // if returnType is not void
}

1) Define and Call Methods

java
public class Calculator {
 
    static int add(int a, int b) {
        return a + b;
    }
 
    public static void main(String[] args) {
        int result = add(10, 20);
        System.out.println(result);  // 30
    }
}

void means no return value.

2) Parameters and Arguments

Parameters are variables in the declaration; arguments are values passed at call time.

java
static void greetUser(String name) {
    System.out.println("Hello, " + name + "!");
}
 
public static void main(String[] args) {
    greetUser("Emma");
    greetUser("Liam");
}

Multiple parameters:

java
static double average(int a, int b, int c) {
    return (a + b + c) / 3.0;
}

3) Return Values

return sends a result back and ends the method.

java
static boolean isPassing(int score) {
    return score >= 60;
}

Methods without return on non-void paths cause compile errors. void methods may use bare return; to exit early.

4) Method Overloading

Overloading = same method name, different parameter lists (type and/or count). Compiler picks the best match at compile time.

java
static int max(int a, int b) {
    return a >= b ? a : b;
}
 
static double max(double a, double b) {
    return a >= b ? a : b;
}
 
static int max(int a, int b, int c) {
    return max(max(a, b), c);
}
java
System.out.println(max(3, 7));       // int version
System.out.println(max(3.5, 2.1));   // double version

Overloading is compile-time polymorphism—preview for Polymorphism.

Warning

Return type alone does not overload a method. Parameter list must differ.

5) static Methods

static belongs to the class, not to one object. Call with ClassName.method() or from another static method in the same class.

java
public class MathUtil {
    static int square(int n) {
        return n * n;
    }
}
 
// Elsewhere
int x = MathUtil.square(5);

main is static because the JVM calls it without creating an object first.

Instance methodstatic method
Called onobjectclass name
Accesses instance fields?yesno (no this object)
Exampledog.bark()Math.max(a, b)

Instance methods and this are covered in Classes.

6) Pass-by-Value

Java passes copies of values (for objects, the copy is a reference value). Primitives do not change in the caller when reassigned inside a method:

java
static void tryToIncrement(int n) {
    n++;
}
 
public static void main(String[] args) {
    int count = 1;
    tryToIncrement(count);
    System.out.println(count);  // still 1
}

Object fields can change if the method mutates the object through the reference.

7) Light Class Example (Preview)

java
public class GreeterDemo {
 
    static class Greeter {
        String name;
 
        Greeter(String name) {
            this.name = name;
        }
 
        void sayHello() {
            System.out.println("Hello, " + name);
        }
    }
 
    public static void main(String[] args) {
        Greeter g = new Greeter("Alice");
        g.sayHello();
    }
}

Only one public top-level class per file; Greeter is a nested helper until Classes.

Common Beginner Mistakes

Missing return on All Paths

java
static int sign(int n) {
    if (n > 0) return 1;
    if (n < 0) return -1;
    // missing return for n == 0
}

Confusing Overload with Override

  • Overload: same class, different parameters (this chapter)
  • Override: child replaces parent method (Inheritance)

Calling Instance Method from static main Without an Object

java
// greet();  // error — need Greeter instance
Greeter g = new Greeter("Tom");
g.sayHello();

Mini Practice

  1. Write static methods celsiusToFahrenheit and overloaded formatTemp for int and double
  2. Overload printLine to accept zero args (print ---) or one String (print that line)

What’s Next

Classes for fields, constructors, and instance methods in depth.

FAQ

What is the difference between a function and a method?

In Java, methods live inside classes (or interfaces). “Function” often means a free-standing procedure in other languages; Java uses methods.

Can methods call other methods?

Yes. main can call any accessible static method; instance methods call others on this object.

Why is main static?

The JVM starts execution without constructing your class first, so it calls ClassName.main on the class itself.

How many overloads should I write?

Only when calls are clearer than many optional parameters. Avoid confusing duplicates.

Do I need to memorize all modifiers now?

Learn public, private, static first; more in Packages.