Java Course

Java Methods (Functions)

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Defining a Method

In Java, functions are called methods and must be defined inside a class. The basic syntax is:

returnType methodName(paramType param1, ...) {
    // body
    return value;
}

Simple Method Example

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

    static double circleArea(double radius) {
        return Math.PI * radius * radius;
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));          // 7
        System.out.println(circleArea(5.0));     // 78.53...
    }
}

void Methods

static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}
// greet("Alice"); → "Hello, Alice!"

Method Overloading

Java allows multiple methods with the same name but different parameter lists:

static int multiply(int a, int b) { return a * b; }
static double multiply(double a, double b) { return a * b; }
static int multiply(int a, int b, int c) { return a * b * c; }

multiply(2, 3);         // calls first → 6
multiply(2.5, 3.0);     // calls second → 7.5
multiply(2, 3, 4);      // calls third → 24

Recursion

static int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
// factorial(5) → 120

Varargs

static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}
sum(1, 2, 3);        // 6
sum(10, 20, 30, 40); // 100