Java Methods

Java
public class Calculator {

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

    public static void greet(String name) {
        System.out.println("Namaste, " + name);
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));  // 7
        greet("Sita");
    }
}

Anatomy

public static int add(int a, int b)

Part Meaning
public Visible everywhere
static Belongs to the class, callable without an object
int Return type (void = returns nothing)
add Method name
(int a, int b) Parameters with declared types

Overloading

Several methods can share a name if their parameter lists differ:

Java
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; }

The compiler picks based on the arguments you pass. Return type alone is not enough to distinguish overloads.

Varargs

Accept any number of arguments:

Java
public static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}

sum(1, 2, 3);      // 6
sum(1, 2, 3, 4, 5); // 15
sum();              // 0

A varargs parameter must be last in the list.

Pass by value — always

Java passes copies. Reassigning a parameter never affects the caller:

Java
static void change(int x) { x = 99; }

int n = 5;
change(n);
System.out.println(n);  // still 5

For objects, the reference is copied — so you can mutate the object, but not repoint the caller's variable:

Java
static void addItem(List<String> list) { list.add("new"); }   // caller sees this
static void replace(List<String> list) { list = new ArrayList<>(); } // caller does NOT

Keep methods small

A method should do one thing and its name should say what. If you need "and" to describe it, it's probably two methods.