← all problems

Predict the Output: Calling Methods 🌶️🌶️

Before you run any of this code, work it out by hand. Every question here is about what actually happens when a program with more than one method runs: which order the lines execute in, what a call is worth once it returns, and what a caller does and does not get to see change.

1. Consider this program:

public static void main(String[] args) {    System.out.println("A");    first();    System.out.println("B");    second();    System.out.println("C");}public static void first() {    System.out.println("one");}public static void second() {    System.out.println("two");}


What prints, in order (one value per line)?

2. Consider this program:

public static void main(String[] args) {    System.out.println(square(3) + 1);}public static int square(int n) {    return n * n;}


What prints?

3. Which of these four methods will NOT compile?

A) public static int square(int n) {       return n * n;   }B) public static int triple(int n) {       return n * 3;       System.out.println("done");   }C) public static void show(int n) {       System.out.println(n);   }D) public static int negate(int n) {       return -n;   }

4. Which of these four methods will NOT compile?

A) public static int cube(int n) {       return n * n * n;   }B) public static int half(int n) {       int result = n / 2;   }C) public static void log(int n) {       System.out.println("value: " + n);   }D) public static int addFive(int n) {       return n + 5;   }

5. Consider this program, using int division from Lesson 03:

public static void show(int x)    { System.out.println("int"); }public static void show(double x) { System.out.println("double"); }show(7);show(7.0);show(7 / 2);show(7 / 2.0);


What prints, in order (one value per line)?

6. Consider this program:

public static void main(String[] args) {    int total = 10;    addFive(total);    System.out.println(total);}public static void addFive(int n) {    n = n + 5;}


What prints?

7. Now consider this version instead:

public static void main(String[] args) {    int total = 10;    total = addFive(total);    System.out.println(total);}public static int addFive(int n) {    return n + 5;}


What prints?

Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.