Lesson 4 / 11

Methods and Parameters

A method is Java’s term for a function defined inside a class — in Java, every single function you write lives inside some class, there’s no such thing as a standalone function floating outside a class definition.

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

// calling it:
int total = MathHelper.add(2, 3);   // 5

Return types

Every method declares exactly what type it returns — int, String, a custom object, or void if it returns nothing at all. Unlike Python, a Java method can never sometimes return a value and sometimes not — the compiler enforces that every code path through the method returns the declared type consistently.

public static void printGreeting(String name) {
    System.out.println("Hello, " + name + "!");
}

Access modifiers

public methods can be called from anywhere; private methods can only be called from within the same class. You’ll use private constantly once you reach the object-oriented programming lesson, to hide internal implementation details from code outside the class.

Overloading

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

Java lets you define multiple methods with the same name as long as their parameter lists differ — either in type, or in the number of parameters. This is method overloading, and the compiler figures out which version to call based on what arguments you actually pass in at each call site.

Static vs instance methods

A static method belongs to the class itself and can be called without ever creating an object, exactly like MathHelper.add(2, 3) above. A non-static (instance) method belongs to a specific object and can only be called on one — you’ll see the difference clearly once you reach the classes lesson.