Methods, Parameters, Return Values, and Varargs

A method should perform one coherent operation and expose a clear contract. Java passes arguments by value. For object arguments, the copied value is the reference itself.

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

static int sum(int... values) {
    int total = 0;
    for (int value : values) total += value;
    return total;
}

Varargs are compiled as an array parameter and must be the final parameter.

Pass-by-value

Java never passes variables by reference. A reference value can be copied, and both variables can point to the same object.

Key Takeaways
  • Java is strictly pass-by-value.
  • Varargs provide convenient variable-length arguments.
  • Method contracts should make inputs, outputs, and failure behavior explicit.