Chapter 3.2: Methods

Chapter 3.2: Methods · Study Questions
Parameters and argumentsreturn and voidOverloadingThe call stackMath methodsScopeDesign
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · The Method Concept

Question 1: Parameter and Argument

Which statement about this call is true?

static int square(int x) {
    return x * x;
}
// in main:
int a = 3;
int b = square(a + 1);

B: The x in the definition is the parameter; the expression in the call is the argument. The argument is evaluated first (4), and its value is copied into x in the new frame; the method returns 16 and b gets 16. a stays 3.

Multiple Choice · Definition and Call

Question 2: A Valid Method Header

Which of the following is a valid method header?

C: The order is: modifiers, return type, name, parameter list. Every parameter needs its own type (int a, b is not allowed). The return type is mandatory; only a constructor, which has the same name as its class, goes without one. The return type cannot come before the modifiers.

Multiple Choice · Definition and Call

Question 3: The return Rules

Which of the following methods compiles?

A: In a void method, a bare return; exits the method early. In the second one the two conditions cover every case, but the compiler does not reason about the values of conditions; with no return at the end it reports missing return statement. A void method cannot return a value, and an int method cannot finish with a bare return;.

Multiple Choice · Definition and Call

Question 4: Which print Runs?

There are three overloaded methods. What do the four calls print?

static void print(int a) {
    System.out.print("I");
}
static void print(long a) {
    System.out.print("L");
}
static void print(double a) {
    System.out.print("D");
}
// in main:
print(5); print(5L);
print(5.0f); print('A');

D: The compiler looks at the argument's type: 5 is an int → I; 5L is a long → L. 5.0f is a float; there is no float version, so the nearest widening, double, is chosen → D. 'A' is a char; a char widens to int first → I. The choice is made at compile time.

Step-by-Step Trace · Definition and Call

Question 5: Tracing Pass by Value

Both the method and main use a variable named number. Trace the call stack. What does the program print?

main's local number is 5.

A new frame: the parameter number is a copy of main's value. Same name, but two separate variables.

Only the copy becomes 15.

The frame closes. The returned 15 is assigned to no variable, so it is lost.

main's number never changed.

In the second call the copy becomes 15 as well.

This time the returned value is assigned to main's number.

A method's result reaches the caller only if it is returned and assigned.

static int increase(int number) {
    number += 10;
    return number;
}
// in main:
int number = 5;
increase(number);
System.out.println(number);
number = increase(number);
System.out.println(number);

Output Question · Definition and Call

Question 6: Decoding a Student Number

In a nine-digit number, the first two digits are the enrollment year, the fourth digit from the end is the department code, and the last three digits are the enrollment order. What does the program print?

static int enrollmentYear(int no) {
    return no / 10000000 + 2000;
}
static int enrollmentOrder(int no) {
    return no % 1000;
}
static String department(int no) {
    int code = (no / 1000) % 10;
    if (code == 7) return "Electrical";
    if (code == 6) return "Computer";
    return "Unknown";
}
// in main:
int no = 240706045;
System.out.println(enrollmentYear(no) + " "
        + enrollmentOrder(no));
System.out.println(department(no) + " / "
        + department(no + 1000));
Show answer
2024 45
Computer / Electrical
  • 240706045 / 107 = 24 → 2024. 240706045 % 1000 = 45: a number does not keep the leading zero (045).
  • 240706045 / 1000 = 240706, % 10 = 6 → Computer. no + 1000 = 240707045 → code 7.
  • Each method does one job and returns its result; the printing stays in main.

Step-by-Step Trace · Methods Calling Methods

Question 7: Tracing the Call Stack

The methods call each other. Trace how the frames open and close. What does the program print? What is the maximum number of frames on the stack?

main calls difference(2, 3); 2 and 3 are copied into a and b.

Both operands of the subtraction are needed; the left one first: cube(2).

For n * square(n), square(2) is called.

The deepest moment: 4 frames. square(2) returns 4.

cube(2) = 2 · 4 = 8 returns; its frame closes.

Now the right operand: square(3). The new frame has its own n, 3, and returns 9.

8 − 9 = −1 is returned.

The returned −1 is printed; only main is left on the stack.

static int square(int n) {
    return n * n;
}
static int cube(int n) {
    return n * square(n);
}
static int difference(int a, int b) {
    return cube(a) - square(b);
}
// in main:
System.out.println(difference(2, 3));

Output Question · Methods Calling Methods

Question 8: Nested Calls

The result of one method becomes the argument of another. What does the program print?

static int power(int base, int exp) {
    int result = 1;
    for (int i = 0; i < exp; i++)
        result *= base;
    return result;
}
static int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++)
        result *= i;
    return result;
}
// in main:
System.out.println(factorial(power(2, 2)));
System.out.println(power(factorial(3), 2));
System.out.println(
        power(power(2, 2), factorial(2)));
Show answer
24
36
16
  • The inner call runs first: power(2, 2) = 4 → factorial(4) = 24.
  • factorial(3) = 6 → power(6, 2) = 36. The order of the arguments matters: power(2, 6) would be 64.
  • Arguments are evaluated left to right: power(2, 2) = 4, factorial(2) = 2 → power(4, 2) = 16.

Multiple Choice · Methods Calling Methods

Question 9: A Wrong Combination

combination(5, 2) gives the correct result (10), but combination(13, 2) returns 24 instead of 78. Why?

static int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++)
        result *= i;
    return result;
}
static int combination(int n, int r) {
    return factorial(n)
         / (factorial(r) * factorial(n - r));
}

A: 13! = 6227020800 exceeds the int limit (2147483647) and silently becomes 1932053504. 2! · 11! = 79833600 fits in an int; 1932053504 / 79833600 = 24. The fix: use long, or compute C(n, r) step by step by multiplying and dividing.

Multiple Choice · Built-in Methods

Question 10: Math and Integer Division

What does System.out.println(Math.sqrt(16) + Math.max(3, 7) / 2); print?

B: Math.max(3, 7) takes two ints, so it returns an int: 7. 7 / 2 is integer division: 3. Math.sqrt always returns a double: 4.0. 4.0 + 3 = 7.0.

Output Question · Built-in Methods

Question 11: Absolute Value and Overflow

Our own method is compared with Math.abs. What does the program print?

static int absoluteValue(int number) {
    if (number < 0) {
        return -number;
    } else {
        return number;
    }
}
// in main
System.out.println(absoluteValue(-3) + " "
        + absoluteValue(3));
System.out.println(
        absoluteValue(Integer.MIN_VALUE));
System.out.println(Math.abs(Integer.MIN_VALUE));
System.out.println(Math.abs(-7.5));
System.out.println(
        Math.abs((long) Integer.MIN_VALUE));
Show answer
3 3
-2147483648
-2147483648
7.5
2147483648
  • The int range is −2147483648 … 2147483647: the positive counterpart of the smallest value does not fit in an int. -number overflows and is again −2147483648; Math.abs(int) gives the same result.
  • Math.abs is overloaded: with a double argument the double version is called (7.5), and with a long argument the long version (2147483648 fits in the long range).

Multiple Choice · Scope

Question 12: Which Code Compiles?

Which of these fragments, written inside main, compiles?

D: A variable lives in the block where it is declared. The ts of two sibling blocks are in separate scopes and do not clash. An inner block cannot reuse the name of an outer local variable (already defined). A loop variable does not exist after the loop (cannot find symbol). A local variable cannot be read before it gets a value.

Step-by-Step Trace · Scope

Question 13: Tracing Shadowing

A class field, a parameter and a local variable share one name. Which x is which? What does the program print?

The class field x lives for the whole program.

main's local x shadows the field: inside main, x means this variable.

f's parameter x is a copy of 5. The local copy becomes 15; the field is untouched.

f prints its own x.

g has no local variable with this name: x refers to the class field, which becomes 101.

g prints the field's new value: 101.

main's x is still 5. The shadowed field is reached with Scope.x.

public class Scope {
    static int x = 1;
    static void f(int x) {
        x = x + 10;
        System.out.print(x + " ");
    }
    static void g() {
        x = x + 100;
        System.out.print(x + " ");
    }
    public static void main(String[] args) {
        int x = 5;
        f(x);
        g();
        System.out.println(x + " " + Scope.x);
    }
}

Multiple Choice · Abstraction and Design

Question 14: Good Method Design

Of these methods for the average of three grades, which best follows good design principles?

C: A good method does one job, takes its input through parameters, returns its result and has a name that says what it does. Because the result is returned, it can be used in other computations too. "Compute and print", hidden dependence on fields and a meaningless name like operation2 all break these principles.

Coding Question · Abstraction and Design

Question 15: The Next Prime

Split the problem into two methods: boolean isPrime(int number) and int nextPrime(int n), which uses it to return the first prime greater than n. What are nextPrime(20), nextPrime(23) and nextPrime(1)?

Show answer
static boolean isPrime(int number) {
    if (number < 2) return false;
    for (int i = 2; i * i <= number; i++)
        if (number % i == 0) return false;
    return true;
}
static int nextPrime(int n) {
    int candidate = n + 1;
    while (!isPrime(candidate)) candidate++;
    return candidate;
}

Results: 23, 29 (not n itself, but the first prime greater than it), 2.

nextPrime does not know how primality is tested; it only trusts what isPrime returns (functional abstraction). Even if isPrime is rewritten to be faster, nextPrime stays the same.

Multiple Choice · Abstraction and Design

Question 16: A Missing Condition in the Prime Check

findNextPrime(20) gives the correct result (23). What do findNextPrime(0) and findNextPrime(-4) return?

static int findNextPrime(int number) {
    int next = number + 1;
    while (!isPrime(next)) {
        next++;
    }
    return next;
}
static boolean isPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

D: For numbers below 2, the loop in isPrime never runs and it returns true. findNextPrime(0) accepts its first candidate, 1, as "prime"; findNextPrime(-4) accepts −3. The correct result should have been 2 in both cases (A). The fix: put if (number < 2) return false; at the start of isPrime. findNextPrime does not change; the bug is only in the method it uses.

The End

Chapter 3.2: Methods: Study Questions
Lecture slides: Chapter 3.2: Methods · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.