Lesson content
Read, practise, then check your understanding
A method declares modifiers, return type, name, parameters, optional exceptions, and a body. Java always passes arguments by value: an object-reference value is copied, so a method can mutate the referenced object but cannot replace the caller’s variable.
Contracts and recursion
static long factorial(int n) {
if (n < 0) throw new IllegalArgumentException("negative n");
if (n <= 1) return 1;
return Math.multiplyExact(n, factorial(n - 1));
}
static int sum(int... values) {
int total = 0;
for (int value : values) total += value;
return total;
}
Overloads share a name but differ in parameter lists; return type alone is insufficient. Resolution uses compile-time argument types and applicable conversions. Varargs must be last and are represented as an array. Recursion needs a base case and progress; Java does not guarantee tail-call optimization, so deep recursion can overflow the stack. Keep methods focused, validate public boundaries, minimize hidden state, and document non-obvious preconditions and failure behavior.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.