Skip to content

Chapter 6 of 37

Methods

Design signatures, parameters, return values, overloads, varargs, and recursion.

34 minutes 10 quick checksBy Subha Prasad
Lesson 6 of 37Course navigation

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.

Which statement best describes method signature?
Which Java term matches this description: A method name together with its parameter types.
Which statement best describes overloading?
Which Java term matches this description: Declaring same-named methods with different parameter lists.
Which statement best describes recursion?
Which Java term matches this description: A method solving a problem by calling itself on a smaller case.
Which statement best describes varargs?
Which Java term matches this description: A final parameter that accepts zero or more values as an array.
Which statement best describes pass by value?
Which Java term matches this description: Java's rule that every argument value, including an object reference, is copied.

0 of 10 checks passed

Your progress is saved on this device.

Methods | Java Lesson | Subha Prasad