Consider the following Java method call sequence. What will be printed to the console?
public class StackTest { public static void main(String[] args) { methodA(); } static void methodA() { int x = 5; methodB(x); } static void methodB(int y) { y += 10; System.out.println(y); } }
Remember that methodB receives a copy of the value passed from methodA.
The variable y in methodB is a copy of x from methodA. Since y is 5 initially, adding 10 results in 15, which is printed.
What will be the output of this Java program?
public class StackMemoryDemo { public static void main(String[] args) { int a = 3; int b = multiplyByTwo(a); System.out.println(b); } static int multiplyByTwo(int num) { int result = num * 2; return result; } }
Think about what the method returns and what is printed.
The method multiplyByTwo returns num * 2, which is 6. This value is stored in b and printed.
Analyze the following Java code and determine what it prints.
public class RecursionStack { public static void main(String[] args) { printNumbers(3); } static void printNumbers(int n) { if (n == 0) return; System.out.print(n + " "); printNumbers(n - 1); } }
Look at the order of the print statement and the recursive call.
The method prints n before calling itself with n-1, so it prints 3, then 2, then 1, stopping before 0.
What will happen when running this Java program?
public class StackOverflowDemo { public static void main(String[] args) { recurse(); } static void recurse() { recurse(); } }
Think about what happens when a method calls itself endlessly without stopping.
The method recurse calls itself infinitely, causing the call stack to grow until it exceeds its limit, throwing a StackOverflowError.
Which statement best describes how Java uses stack memory during method execution?
Think about what happens when a method is called and when it finishes.
Java creates a new stack frame for each method call to hold local variables and parameters. When the method finishes, its frame is removed from the stack.
