Java - Methods

Methods

Signatures and Parameters

A method’s signature is its name and parameter types (not including return type).

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

Overloading

Multiple methods with the same name but different parameter lists.

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

Pass-by-Value (Always)

Java passes arguments by value. For objects, the value is a copy of the reference.

void setToZero(int x) { x = 0; }
void addItem(java.util.List xs) { xs.add("a"); }
int a = 5; setToZero(a); // a remains 5
var list = new java.util.ArrayList();
addItem(list); // list mutated; now contains "a"

Varargs

static int sumAll(int... xs) { int s=0; for (int x: xs) s+=x; return s; }
int total = sumAll(1,2,3,4);

Recursion

static int fact(int n) { return (n <= 1) ? 1 : n * fact(n-1); }

Javadoc

/** Adds two integers. @param a left @param b right @return sum */
static int add(int a, int b) { return a + b; }
Avoid excessive parameter lists. Consider grouping parameters into a value object or builder for clarity.

Try it

  1. Write a sumAll(int... xs) method and test with different inputs.
  2. Show pass-by-value by attempting to reassign a parameter and printing the original variable.