Chapter 9: Methods
Multiple Choice · Method Basics
Question 1: Order of Calls
The method both prints to the screen and returns a value. What is the output?
static int f(int x) { System.out.print("f" + x + " "); return x * 2; } // inside main: System.out.println(f(1) + f(2));
C: While println's argument is evaluated, f(1) is called first (left to right), then f(2); each prints its own text. Then 2 + 4 = 6 is printed. D would happen in an expression that starts with a String, like "s=" + f(1) + f(2) (String concatenation: "24").
Multiple Choice · Method Basics
Question 2: Non-static Method
What happens when the program is compiled?
public class Example { void greet() { System.out.println("Hello"); } public static void main(String[] args) { greet(); } }
D: main is static (it runs without an object); the non-static greet() belongs to an object and cannot be called directly. The fix is to make the method static void greet().
Step-by-Step Trace · Method Basics
Question 3: power(2, −2)
For a negative exponent the method calls itself with the positive exponent. What does power(2, -2) return? Trace the call stack.
main calls power(2, -2). The int 2 widens to 2.0 for the double parameter.
New frame: base = 2.0, exp = −2, result = 1.0.
exp < 0 → the method calls itself with −exp = 2. The new frame on top has its own base, exp and result boxes.
exp = 2 ≥ 0 → for: i = 0, result = 1.0 × 2.0 = 2.0.
i = 1, result = 4.0. Then i = 2 < 2 is false.
return 4.0: the top frame closes.
The first frame resumes where it left off: result = 1.0 / 4.0 = 0.25. (Because 1.0 is written, the division is a double division.)
return 0.25: the frame closes.
0.25 is printed: 2⁻² = 1 / 2² = 1/4. (The method is declared static so main can call it.)
static double power(double base, int exp) { double result = 1; if (exp < 0) { result = 1.0 / (power(base, -exp)); } else { for (int i = 0; i < exp; i++) { result *= base; } } return result; } // main: System.out.println(power(2, -2));
Multiple Choice · Return Values
Question 4: Which One Compiles?
Which of the following methods compiles without errors?
D: Every path returns an int. A: no return on the n ≤ 0 path → missing return statement. B: a void method cannot return a value → unexpected return value. C: a double is not narrowed to int automatically → possible lossy conversion.
Output Question · Return Values
Question 5: Factorial of a Negative Number
This solution is called with number = -3. What is the output? What is missing in the method?
public static long factorial(int number) { if (number < 0) { System.out.println("Number cannot be negative."); } long result = 1; for (int i = 1; i <= number; i++) { result *= i; } return result; } // inside main: int number = -3; System.out.println(number + " factorial: " + factorial(number));
Show answer
Number cannot be negative. -3 factorial: 1
- println's argument is evaluated before anything is printed: factorial is called and prints the warning first.
- After the warning the method continues; the for loop never runs → it returns 1, so a wrong result appears on screen.
- Missing: an early exit inside the if with
return -1;(or an exception).
Step-by-Step Trace · Return Values
Question 6: choose(4, 2)
choose calls the factorial method three times. Trace the call stack and the returned values.
main calls choose(4, 2).
Frame: n = 4, r = 2. To evaluate the expression, factorial(n) is needed first.
New frame: n = 4 (a separate box from choose's n). result = 2·3·4 = 24.
24 is returned and the frame closes. The next call is factorial(r) = factorial(2).
n = 2: result = 2 → returns 2.
factorial(n − r) = factorial(2): the same method, a brand-new frame → 2.
24 / (2 × 2) = 24 / 4 = 6. return 6.
6 is printed: the number of ways to choose 2 of 4 items. Calling another method avoids code repetition.
static long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } static long choose(int n, int r) { return factorial(n) / (factorial(r) * factorial(n - r)); } // main: System.out.println(choose(4, 2));
Output Question · Parameters
Question 7: The swap Trap
What is the output of the following code?
static void swap(int a, int b) { int t = a; a = b; b = t; } // inside main: int x = 3, y = 5; swap(x, y); System.out.println(x + " " + y);
Show answer
Output: 3 5
- a and b are copies of x and y; swap exchanges its own copies.
- When the method ends, a, b and t are discarded; x and y in main were never touched.
Multiple Choice · Parameters
Question 8: Invalid Overloading
Which pair of methods in the same class causes a compile error?
C: Signature = name + parameter list; the return type is not part of the signature. Both are area(int), so even if never called the second declaration does not compile: method area(int) is already defined. A differs by count, B by type, D by order.
Step-by-Step Trace · Parameters
Question 9: Which show Is Called?
For each call the compiler picks the method that matches the type and number of the arguments. Find the output.
show(5): a single int argument → exact match show(int).
show(5.0): 5.0 is a double literal → show(double). Since it is a double, 5.0 is printed.
show(3, 4): two arguments → show(int, int). Thanks to the parentheses 3 + 4 = 7 is added (otherwise it would be "two 34").
show('A'): no exact match for char; the char → int widening is the closest option. 'A' = 65.
show(7L): a long does not narrow to int automatically but widens to double → show(double).
The choice is made at compile time, before the program runs. If no signature matches (e.g. show("a")) it is a compile error.
static void show(int x) { System.out.println("int " + x); } static void show(double x) { System.out.println("double " + x); } static void show(int a, int b) { System.out.println("two " + (a + b)); } // main: show(5); show(5.0); show(3, 4); show('A'); show(7L);
Multiple Choice · Parameters
Question 10: larger(3, 4.5)
The class has static int larger(int a, int b) and static double larger(double a, double b). What does System.out.println(larger(3, 4.5)); print?
B: 4.5 is a double, so larger(int, int) does not fit; 3 is widened to double and larger(double, double) is called → 4.5. larger(3, 4) would pick the int version and print 4.
Multiple Choice · Scope
Question 11: Variable Used Outside Its Block
Which line causes a compile error?
static int compute(int n) { // 1 int result = 0; // 2 if (n > 0) { // 3 int bonus = n * 2; // 4 result += bonus; // 5 } // 6 return result + bonus; // 7 }
C: bonus is defined in the if block and disappears when the block closes (line 6): cannot find symbol: bonus. Line 5 is valid; the inner block sees result from the outer scope.
Step-by-Step Trace · Scope
Question 12: static Field and Local Variable
There is a class-level static int x and a local x with the same name in the method. Find the output step by step.
static field x = 10: it belongs to the class and all methods can see it.
g is called: a local x = 3 is declared. The local name shadows the field of the same name inside the method (it compiles).
x++ increments the local box → 4 is printed. The field is still 10.
g is done and the local x is gone. In main, x refers to the field → 10.
The field is updated: x = 11.
g is called again: the local x is created afresh with 3 on every call → 4 again.
Output: 4, 10, 4, 11. Shadowing happens only between a local variable and a field; two local variables cannot share a name in the same scope.
static int x = 10; static void g() { int x = 3; x++; System.out.println(x); } // main: g(); System.out.println(x); x = x + 1; g(); System.out.println(x);
Output Question · Scope
Question 13: Same Names, Separate Boxes
What is the output of the following code?
static int square(int a) { int b = a * a; return b; } // inside main: int a = 3, b = 4; b = square(b); System.out.println(a + " " + b);
Show answer
Output: 3 16
- square's a is a copy of main's b (4); square's b is 16.
- main's a (3) never changes; main's b becomes 16 through the return value.
Step-by-Step Trace · Example Methods
Question 14: previousPrime(100)
previousPrime(100) is called. How many times is isPrime called and what is returned?
The search starts one below 100: 99.
99 % 2 = 1, 99 % 3 = 0 → return false (early return).
Not prime → previous-- → 98.
98 % 2 = 0 → false.
previous → 97.
i = 2..96 (95 trials): none divides 97 → true.
if true → return 97. isPrime was called 3 times; return ends both the loop and the method.
static boolean isPrime(int number) { if (number <= 1) return false; for (int i = 2; i < number; i++) if (number % i == 0) return false; return true; } static int previousPrime(int number) { int previous = number - 1; while (previous > 1) { if (isPrime(previous)) return previous; previous--; } return -1; }
Output Question · Example Methods
Question 15: previousPrime Boundary Values
With the same previousPrime and isPrime, what is the output?
System.out.println(previousPrime(20)); System.out.println(previousPrime(3)); System.out.println(previousPrime(2));
Show answer
19 2 -1
- 20 → 19 is prime (nothing divides 19).
- 3 → previous = 2; 2 > 1 is true, isPrime(2): the for loop never runs (2 < 2 is false) → true → 2.
- 2 → previous = 1; 1 > 1 is false → the loop is not entered,
return -1(the "not found" marker).
Multiple Choice · Example Methods
Question 16: How Many Rounds Does isPrime Run?
97 is prime. For 97, how many times does each version compute a remainder: the common for (int i = 2; i < number; i++) version and the for (int i = 2; i <= n / i; i++) version from the lecture?
A: The first runs i = 2..96 → 95 rounds. The second runs while i × i ≤ 97 (i = 2..9; 10 <= 97/10 = 9 is false) → 8 rounds. If there is a divisor larger than √n, a smaller partner exists too, so checking up to √n is enough. The result (true) is the same.
Output Question · Example Methods
Question 17: gcd and lcm
What is the output of the following code?
static int gcd(int a, int b) { while (b != 0) { int r = a % b; a = b; b = r; } return a; } static int lcm(int a, int b) { return a / gcd(a, b) * b; } // inside main: System.out.println(gcd(84, 36) + " " + lcm(4, 6));
Show answer
Output: 12 12
- 84 % 36 = 12 → (36, 12); 36 % 12 = 0 → (12, 0) → gcd = 12.
- lcm(4, 6): gcd(4, 6) = 2 → 4 / 2 * 6 = 12. Dividing first avoids an a·b overflow.
Output Question · Example Methods
Question 18: Nested Call and Counter
The static field counter increases on every call. What is the output?
static int counter = 0; static int twice(int n) { counter++; return n * 2; } // inside main: int r = twice(twice(3)); System.out.println(r + " " + counter);
Show answer
Output: 12 2
- In a nested call the inner one runs first: twice(3) → 6 (counter = 1).
- Then twice(6) → 12 (counter = 2).
- Since counter is a static field, it keeps its value between calls; a local variable would start from 0 on every call. This is a side effect.
Multiple Choice · Example Methods
Question 19: Pure Method
Which of the following methods is pure (always returns the same result for the same input and does not change outside state)?
B: It looks only at its parameter and returns a value; square(4) is always 16, it can be used anywhere and is easy to test. A prints to the screen (side effect), C changes a field, D gives a different result on every call.
Multiple Choice · Example Methods
Question 20: Integer Division in an Average
static double average(int a, int b, int c) { return (a + b + c) / 3; }, what does average(7, 8, 8) return?
C: (a + b + c) / 3 = 23 / 3 is integer division between two ints → 7; then, because the return type is double, it becomes 7.0. Fix: (a + b + c) / 3.0 → 7.666666666666667. A double return type does not turn the division into floating-point division by itself.