EMZETT.
Login

Methods

In short: A named, reusable unit of code within a class — defines a return type, a name, and optional parameters.

In more detail: Signature structure: accessModifier returnType name(parameters) { ... }, e.g. public int sum(int a, int b) { return a + b; }. If a method returns nothing, void is used instead of a concrete type.

In Depth

public class Calculator {
    // public: callable from anywhere | int: return type | (int a, int b): parameters
    public int sum(int a, int b) {
        return a + b; // return immediately ends the method and delivers the value
    }
 
    // void: returns nothing - "return;" (with no value) is still allowed, to exit early
    public void greet(String name) {
        if (name == null || name.isBlank()) {
            System.out.println("No name given");
            return; // early exit, no value
        }
        System.out.println("Hello, " + name);
    }
 
    // static: belongs to the class, not an instance - callable without "new Calculator()"
    public static int square(int x) {
        return x * x;
    }
}
 
int result = new Calculator().sum(3, 4); // instance method - needs an object
int q = Calculator.square(5);          // static method - directly via the class name

The difference between instance methods and static methods is fundamental: an instance method implicitly works with the state of ONE specific object (it can access its fields, via the invisible this), a static method belongs to the class as a whole and has NO access to instance fields, since it can be called with no concrete object at all. A method with void as the return type may still contain a lone return; (with no value), to exit the method early — common for guard clauses (early validation checks at the start of a method), which avoid nested if structures.

See also: Parameters, void, Overloading, Classes