Methods in Java

Site Admin · 11 Sep 2026 · 12 views

Why Methods

Methods group statements into named, reusable units. They let you write logic once and call it from many places, which keeps programs shorter and easier to test.

Defining and Calling a Method

public class Calculator {

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

    public static void main(String[] args) {
        int result = add(7, 5);
        System.out.println("Sum: " + result);
    }
}

Parameters and Arguments

Java passes arguments by value: a copy of the value is handed to the method. For primitives the original variable never changes.

static void tryChange(int n) {
    n = 99;
}
int x = 5;
tryChange(x);
System.out.println(x); // still 5

Method Overloading

You can define several methods with the same name as long as their parameter lists differ.

static String greet(String name) { return "Hello " + name; }
static String greet(String name, String title) { return "Hello " + title + " " + name; }

greet("Priya");          // Hello Priya
greet("Priya", "Dr.");   // Hello Dr. Priya

Recursion

A method that calls itself is recursive. Every recursive method needs a base case to stop.

static int factorial(int n) {
    if (n <= 1) return 1;   // base case
    return n * factorial(n - 1);
}

Variable Arguments (varargs)

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

Key Points

  • A method has a return type, a name, and a parameter list.
  • Arguments are passed by value.
  • Overloading lets one name serve multiple parameter shapes.
Share this post:

Comments (0)

Please login or register to comment.