Methods in Java — exercises with a converter, a week of temperatures and the guessing game of 31 (and the return the compiler couldn’t see)

My first method with an if / else if gave me missing return statement and I spent a good while staring at it, because for me the two conditions covered every case: either the grade is greater than or equal to 5, or it’s less than 5. What else is there? I deleted it, wrote it again the same way and it failed again. The compiler doesn’t do that maths: what looks obvious to you is, for it, a path left with no way out. You’ll see it in the first “What’s wrong here?” snippet.

Today it’s your turn. There are three exercises that climb little by little: a converter to warm up, a week’s statistics without storing the data (arrays come in the next topic) and, to finish, Laura’s guessing game, which has been waiting since flow control for its repeated block to become methods. Before the solutions there are three snippets with a catch, and at the end an exam-style quiz and the cheat sheet. If you need to review, there’s the theory and the methods in Java practice.

How to use this article

  1. Read the statement and the expected output; type the same data to compare.
  2. Give it at least 15 minutes before opening the hint.
  3. Also try the odd cases: the impossible value, the one right on the limit, the game you lose.
  4. Compare with the solution and read the reason behind each decision: that’s where you learn the most.

The three exercises read from the keyboard with Scanner and were run once on a computer set to Spanish, so decimals are typed with a comma (36,6) and printed with a comma. On an English-language computer you’d type and see a point. Each solution is a single class with its main: you can open it in the website’s Java playground with the “Open in the playground” button.

Methods in Java exercises — Basic level

Exercise 1 — Temperature converter

Write a program that asks for a temperature in degrees Celsius and shows it in Fahrenheit and in Kelvin. Each conversion goes in its own method, and another method checks that the temperature is possible: nothing can be below absolute zero, −273.15 °C. The formulas: F = C × 9 / 5 + 32 and K = C + 273.15.

Expected output with 36,6 °C:

=== TEMPERATURE CONVERTER ===
Temperature in °C: 36,6

--- Result ---
36,6 °C = 97,9 °F
36,6 °C = 309,75 K

With −300, the program warns and ends without converting anything:

=== TEMPERATURE CONVERTER ===
Temperature in °C: -300
There is no temperature below -273.15 °C

Write three methods: isValidTemperature (returns boolean), celsiusToFahrenheit and celsiusToKelvin (return double). The conversion ones don’t print anything: they only calculate and return, and main is the one that prints. Validate first and, if it isn’t valid, cut it short with return in main. And watch out for 9 / 5: between two integers it gives 1.

Methods in Java exercises — Intermediate level

Exercise 2 — The week’s statistics

Write a program that asks for the maximum temperature of each of the 7 days of the week (integers) and shows the highest, the lowest, the average with two decimals and how many days went above 22 °C. A temperature below −50 or above 60 is a typing error: warn and ask for the same day again. No arrays: there’s no need to store the seven values, it’s enough to keep a few variables up to date in each round.

Each task goes into a method: reading and validating one day, the larger of two numbers, the smaller of two numbers, the average from the sum, and whether a temperature is above the threshold.

Expected output with 21, 24, 19, a 70 that is rejected and then 27, 25, 18 and 22:

=== THIS WEEK'S TEMPERATURES ===
Day 1: 21
Day 2: 24
Day 3: 19
Day 4: 70
  Out of range (-50 to 60). Repeat day 4.
Day 4: 27
Day 5: 25
Day 6: 18
Day 7: 22

--- Statistics ---
Maximum: 27 °C
Minimum: 18 °C
Average: 22,29 °C
Days above 22 °C: 3

Five methods: readTemperature(Scanner sc, int day), larger(int a, int b), smaller(int a, int b), average(int sum, int days) and exceedsThreshold(int temperature, int threshold). In main, a for from 1 to 7: on the first day, the maximum and the minimum are that temperature; from the second on, maximum = larger(maximum, t). For the average, convert to double before dividing. And “above 22” is >, not >=.

Starting the maximum at 0 instead of with the first value. With a winter week where every day is below zero, the maximum would come out as 0, a value that wasn’t in your data.

Methods in Java exercises — Final challenge

Exercise 3 — Guess the number

Laura’s guessing game, final version. The program “thinks” of a number from 1 to 100 with new Random(42).nextInt(100) + 1, which always gives 31 (the same as in flow control and loops), and the player has 7 attempts. After each miss it says whether the secret is higher or lower; a number outside 1-100 is warned about and doesn’t use up an attempt. At the end of a game it asks whether you want to play again (with the same secret) and, at the end, shows the best game, the one with the fewest attempts.

Expected output of a session with two games:

=== GUESS THE NUMBER (1-100) ===
Attempt 1/7: 150
Out of range (1-100): it doesn't count.
Attempt 1/7: 50
Lower.
Attempt 2/7: 25
Higher.
Attempt 3/7: 37
Lower.
Attempt 4/7: 31
You got it!
Play again? (y/n): y

Attempt 1/7: 31
You got it!
Play again? (y/n): n

Best game: 1 attempt

If you don’t win any game:

=== GUESS THE NUMBER (1-100) ===
Attempt 1/7: 10
Higher.
Attempt 2/7: 20
Higher.
Attempt 3/7: 30
Higher.
Attempt 4/7: 40
Lower.
Attempt 5/7: 50
Lower.
Attempt 6/7: 60
Lower.
Attempt 7/7: 70
Lower.
No attempts left. It was 31.
Play again? (y/n): n

You didn't win any game.

The program has to be organised into these methods:

  • readInt in two versions (overloading): one that just shows a message and reads an integer, and another that also receives a minimum and a maximum and repeats until the value is inside.
  • hint, which receives the guess and the secret and returns the help text.
  • playRound, which plays a whole game and returns how many attempts it used, or −1 if it didn’t guess.

The version of readInt with a range doesn’t repeat the reading code: it calls the simple version. playRound is a for from 1 to 7; if it guesses, return n leaves the whole method; if the loop ends, it returns −1. In main, a do-while (the first game is always played) and a best variable that starts at −1 and only changes if the game was won and it’s the first win or beats the previous one. The y/n answer is read with sc.next() and compared with equalsIgnoreCase("y"), never with ==.

What’s wrong here?

Before the solutions, three typical mistakes from this topic. Try to predict what happens in each one before reading the explanation.

Mistake 1

public class Classify {

    public static String classify(int grade) {
        if (grade >= 5) {
            return "Pass";
        } else if (grade < 5) {
            return "Fail";
        }
    }

    public static void main(String[] args) {
        System.out.println(classify(7));
    }
}

When compiling:

Classify.java:9: error: missing return statement
    }
    ^
1 error

It’s my anecdote. For us the two conditions cover every integer, but the compiler doesn’t reason with numbers: it sees that the last path is an else if that might not hold and that, in that case, the method would reach the closing brace without returning anything. The little arrow points exactly at that brace. The fix is for the last path to have no condition:

public class Classify {

    public static String classify(int grade) {
        if (grade >= 5) {
            return "Pass";
        }
        return "Fail";    // final path: the compiler sees that something is ALWAYS returned
    }

    public static void main(String[] args) {
        System.out.println(classify(7));
        System.out.println(classify(3));
    }
}
Pass
Fail

Fixing it by adding a return ""; at the end “so it compiles”. It compiles, but if one day a condition fails, the method will return an empty text without warning. Better for the last real case to be the final path.

Mistake 2

public class Triple {

    public static int doubleOf(int x) {
        return x * 2;
    }

    public int tripleOf(int x) {
        return x * 3;
    }

    public static void main(String[] args) {
        System.out.println(doubleOf(4));
        System.out.println(tripleOf(4));
    }
}

When compiling:

Triple.java:13: error: non-static method tripleOf(int) cannot be referenced from a static context
        System.out.println(tripleOf(4));
                           ^
1 error

tripleOf has no static, so it’s an instance method: it needs an object to be called. main is static and has no object. doubleOf works because it does have static. While everything lives in main‘s class, all methods carry static:

public class Triple {

    public static int doubleOf(int x) {
        return x * 2;
    }

    public static int tripleOf(int x) {    // static, like doubleOf and like main
        return x * 3;
    }

    public static void main(String[] args) {
        System.out.println(doubleOf(4));
        System.out.println(tripleOf(4));
    }
}
8
12

In classes and objects you’ll see the other fix: creating an object and calling the method on it (new Triple().tripleOf(4)). It isn’t “worse” or “better”: it depends on whether the method needs an object’s data. Here it doesn’t, so static is right.

Mistake 3

public class Doubler {

    public static int doubleIt(int x) {
        return x * 2;
    }

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

Output:

5

It compiles without a warning and prints 5. doubleIt(n) does calculate 10, but that value is lost because nobody stores it. And n doesn’t change because doubleIt receives a copy of its value in its parameter x. What a method returns has to be collected:

public class Doubler {

    public static int doubleIt(int x) {
        return x * 2;
    }

    public static void main(String[] args) {
        int n = 5;
        n = doubleIt(n);    // what it returns is collected: now n is 10
        System.out.println(n);
    }
}
10

You’ll see it live, frame by frame, in the Python Tutor section.

Commented solutions

Solution Exercise 1

The approach, before the code. Before opening the editor, write only the three headers and ask yourself what goes in and what comes out of each one: isValidTemperature takes a double and answers yes or no; the two conversions take degrees Celsius and return another number. With that, main almost writes itself, in this order: read, validate (and stop if it isn’t valid), convert and print. The obvious path would be to put everything in main with two printf calls and be done. It works, but then the Fahrenheit formula is glued to the printf and you can’t reuse it or test it on its own, which is exactly what the exercise wants you to practice.

import java.util.Scanner;

public class TemperatureConverter {

    // private: internal check. boolean: yes or no.
    private static boolean isValidTemperature(double celsius) {
        return celsius >= -273.15;    // -273.15 °C is absolute zero: there is nothing below it
    }

    // They receive degrees Celsius and RETURN the converted value. They don't print: that way they work for anything.
    public static double celsiusToFahrenheit(double celsius) {
        return celsius * 9.0 / 5.0 + 32;    // 9.0 / 5.0: with 9 / 5 it would be integer division and give 1
    }

    public static double celsiusToKelvin(double celsius) {
        return celsius + 273.15;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("=== TEMPERATURE CONVERTER ===");
        System.out.print("Temperature in °C: ");
        double celsius = sc.nextDouble();

        // It is validated BEFORE converting and cut short with return, as in Flow control
        if (!isValidTemperature(celsius)) {
            System.out.println("There is no temperature below -273.15 °C");
            sc.close();
            return;
        }

        System.out.println();
        System.out.println("--- Result ---");
        System.out.printf("%.1f °C = %.1f °F%n", celsius, celsiusToFahrenheit(celsius));
        System.out.printf("%.1f °C = %.2f K%n", celsius, celsiusToKelvin(celsius));

        sc.close();
    }
}

The maths in the output: 36.6 × 9 / 5 = 65.88; 65.88 + 32 = 97.88, which %.1f shows as 97,9. And 36.6 + 273.15 = 309.75.

Why the conversion methods don’t print. If celsiusToFahrenheit printed inside, it would only be good for printing. By returning the value it’s good for anything: comparing it with a fever, storing it, passing it to another method. main decides what to do with the number.

Why 9.0 / 5.0. With celsius * (9 / 5) + 32, the bracket is worked out first between two int values and gives 1: the converter would return celsius + 32 (68.6 °F for 36.6 °C) and nobody would notice until comparing it with a thermometer. Without brackets, celsius * 9 / 5 also works, because celsius is already a double and infects the rest; with 9.0 / 5.0 you don’t depend on the order.

Why isValidTemperature is private. It’s an internal check of the program; the conversions are public because they’re what another class might want to reuse.

Why the return in main. It’s the early-exit validation from flow control: if the value isn’t valid, warn and finish, without putting the rest of the program inside an else. In a void main, return; without a value is correct.

What does celsiusToFahrenheit(-40) return, and why is it a good test value?

It returns −40.0: −40 × 9 / 5 = −72 and −72 + 32 = −40. It’s the only temperature where both scales match, so if your method gives anything else, the formula is wrong. Together with 0 °C = 32 °F and 100 °C = 212 °F, those are three values you know by heart that check the method in seconds, without a calculator. Notice that you can run that test precisely because the method returns the value instead of printing it.

Solution Exercise 2

The approach, before the code. The key question is: what do I need to remember from one loop iteration to the next? For the maximum, the minimum, the average and the hot days, four variables are enough (maximum, minimum, sum and hotDays), and each day just updates them. Decide that first and the for follows on its own. That leaves the first day: the temptation is to read it before the loop and start the for at 2, but then you write the call to readTemperature twice. With the if (day == 1) there’s a single read and the first value acts as both maximum and minimum, without making up a starting value like the 0 in the mistake above.

import java.util.Scanner;

public class WeekStats {

    // Reads one day's temperature and repeats it until it is reasonable.
    // Receives the Scanner and the day number; returns an already validated temperature.
    public static int readTemperature(Scanner sc, int day) {
        int t;
        do {
            System.out.print("Day " + day + ": ");
            t = sc.nextInt();
            if (t < -50 || t > 60) {
                System.out.println("  Out of range (-50 to 60). Repeat day " + day + ".");
            }
        } while (t < -50 || t > 60);
        return t;
    }

    // The larger of two numbers. Called in every round, it keeps the maximum of the week.
    public static int larger(int a, int b) {
        if (a > b) {
            return a;
        }
        return b;
    }

    public static int smaller(int a, int b) {
        if (a < b) {
            return a;
        }
        return b;
    }

    // (double) BEFORE dividing: with two ints, 156 / 7 would give 22
    public static double average(int sum, int dias) {
        return (double) sum / dias;
    }

    public static boolean exceedsThreshold(int temperature, int threshold) {
        return temperature > threshold;    // > and not >=: a day of exactly 22 doesn't count as hot
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final int DAYS = 7;
        final int THRESHOLD = 22;

        int maximum = 0, minimum = 0, sum = 0, hotDays = 0;

        System.out.println("=== THIS WEEK'S TEMPERATURES ===");
        for (int day = 1; day <= DAYS; day++) {
            int t = readTemperature(sc, day);
            if (day == 1) {
                maximum = t;               // the first value is both maximum and minimum
                minimum = t;
            } else {
                maximum = larger(maximum, t);
                minimum = smaller(minimum, t);
            }
            sum += t;
            if (exceedsThreshold(t, THRESHOLD)) {
                hotDays++;
            }
        }

        System.out.println();
        System.out.println("--- Statistics ---");
        System.out.println("Maximum: " + maximum + " °C");
        System.out.println("Minimum: " + minimum + " °C");
        System.out.printf("Average: %.2f °C%n", average(sum, DAYS));
        System.out.println("Days above " + THRESHOLD + " °C: " + hotDays);

        sc.close();
    }
}

The heart of the program is the loop in main:

for (int day = 1; day <= DAYS; day++) {
    int t = readTemperature(sc, day);
    if (day == 1) {
        maximum = t;             // the first value is both maximum and minimum
        minimum = t;
    } else {
        maximum = larger(maximum, t);
        minimum = smaller(minimum, t);
    }
    sum += t;
    if (exceedsThreshold(t, THRESHOLD)) {
        hotDays++;
    }
}

And this is how the maximum and the minimum evolve round by round, with the same data as the output:

Maximum and minimum without storing the weekSeven columns, one per day, with the temperatures 21, 24, 19, 27, 25, 18 and 22. The maximum starts at 21 and changes to 24 and 27; the minimum starts at 21 and changes to 19 and 18. The days above 22 are 2, 4 and 5: three.One for round per day: readTemperature, larger, smaller and exceedsThresholddaytmaximumminimum> 221212121no2242421yes3192419no4272719yes5252719yes6182718no7222718nomaximum = larger(maximum, t) · minimum = smaller(minimum, t) · sum = 156 · 156 / 7 = 22.29In coral, the round where it changes. Day 4 counts the 27: the 70 was rejected in readTemperature.
Two variables and two methods are enough: there is no need to remember the seven days.
Daytmaximumminimumsumt > 22
121212121No
224242145Yes
319241964No
427 (after rejecting the 70)271991Yes
5252719116Yes
6182718134No
7222718156No

Average: 156 / 7 = 22.2857…, which comes out as 22,29. Days above 22: days 2, 4 and 5, three. Day 7’s 22 doesn’t count because the condition is >.

Why arrays aren’t needed. The maximum, the minimum, the sum and the counter only need this round’s value and their own previous value. What you couldn’t do without storing the data is, for instance, count the days above the average: the average is only known at the end, when the seven days have gone by. That will need the arrays of the next topic, which is why this exercise uses a fixed threshold of 22 °C.

Why readTemperature returns the value instead of adding it itself. Because that way it does a single thing (read a valid value) and main decides what to do with it. If readTemperature updated the sum or the maximum, it would have to receive and return them, and it can’t return four things at once.

Why larger and smaller and not Math.max and Math.min. They exist and would do the same; here they’re written by hand to practice a method with two return statements and no else. In a real program, use Math.max.

Why (double) sum / days. The cast is applied to sum before dividing, so the division is between a double and an int, which gives a double: 22.2857… With (double) (sum / days), the integer division would happen first (156 / 7 = 22) and the cast would arrive too late: 22,00.

Why does readTemperature use do-while and not a plain while?

Because each day is asked for at least once, and that’s exactly what do-while guarantees: it runs the body first and then checks the condition. With a while (t < -50 || t > 60), the condition would be checked before anything had been read, so you’d have to read once outside the loop (the print and the nextInt written twice) or give t an impossible value, like 100, just to get in. With the data from the output, day 4 goes round twice: the 70 is out of range and gets repeated; the 27 is fine and the method returns it.

Solution Exercise 3

The approach, before the code. This one is designed top-down. Start with main: from each game it only needs to know one number, how many attempts were used, or −1 if the game was lost. That already gives you the header of playRound. Then look at what playRound needs for each attempt: a number between 1 and 100 (that’s readInt with a range) and a hint (that’s hint). Each method is born from what the one above asks of it. The obvious path would be a loop with a boolean guessed variable and a break, all inside main; with return n the method leaves as soon as you guess right and returns the value main needs, with no control variables.

import java.util.Random;
import java.util.Scanner;

public class GuessTheNumber {

    // ---------- Overloading: two versions of readInt ----------

    // Version 1: shows the message and reads an integer, whatever it is
    private static int readInt(Scanner sc, String message) {
        System.out.print(message);
        return sc.nextInt();
    }

    // Version 2: repeats until it is between min and max. It doesn't copy the reading: it calls version 1
    private static int readInt(Scanner sc, String message, int min, int max) {
        int value = readInt(sc, message);
        while (value < min || value > max) {
            System.out.println("Out of range (" + min + "-" + max + "): it doesn't count.");
            value = readInt(sc, message);
        }
        return value;
    }

    // Returns the hint; the case of guessing right is handled before calling it
    private static String hint(int attempt, int secret) {
        if (guess < secret) {
            return "Higher.";
        }
        return "Lower.";
    }

    // ONE complete game: the block that was copied three times in Flow control, written once.
    // Returns how many attempts it used if it guesses, or -1 if it runs out.
    private static int playRound(Scanner sc, int secret, int maxAttempts) {
        for (int n = 1; n <= maxAttempts; n++) {
            // readInt with a range doesn't let a 150 through: that attempt doesn't use up a round of the for
            int attempt = readInt(sc, "Attempt " + n + "/" + maxAttempts + ": ", 1, 100);
            if (guess == secret) {
                System.out.println("You got it!");
                return n;    // leaves the whole method, with the number of attempts
            }
            System.out.println(hint(guess, secret));
        }
        System.out.println("No attempts left. It was " + secret + ".");
        return -1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final int MAX_ATTEMPTS = 7;
        // Seed 42: the same 31 from Flow control and Loops. It is chosen ONCE for the whole session.
        final int SECRET = new Random(42).nextInt(100) + 1;
        int best = -1;    // -1 = "I haven't won any yet"
        String again;

        System.out.println("=== GUESS THE NUMBER (1-100) ===");
        do {
            int used = playRound(sc, SECRET, MAX_ATTEMPTS);
            // It only counts if it won, and if it is the first win or beats the previous one
            if (used != -1 && (best == -1 || used < best)) {
                best = used;
            }
            System.out.print("Play again? (y/n): ");
            again = sc.next();
            System.out.println();
        } while (again.equalsIgnoreCase("y"));    // equalsIgnoreCase, never == with String

        if (best == -1) {
            System.out.println("You didn't win any game.");
        } else {
            System.out.println("Best game: " + best + (best == 1 ? " attempt" : " attempts"));
        }
        sc.close();
    }
}

Who calls whom:

Who calls whom in the guessing gamemain calls playRound once per game and gets n or -1 back. playRound calls readInt with a range and hint on every attempt. The ranged version of readInt calls the simple two-parameter version.maindo-while: one round per gameplayRound(sc, secret, 7)returns n or -1for: one attempt per roundreadInt(sc, msg, 1, 100)hint(guess, secret)readInt(sc, msg)overloading: the 4-arg one uses the 2-arg one"Higher." / "Lower."Each method does one thing: main keeps the best game, playRound knows the rules,readInt knows how to read and validate, and hint only decides the text.
Four small methods instead of a 60-line main.

The two versions of readInt:

private static int readInt(Scanner sc, String message) {
    System.out.print(message);
    return sc.nextInt();
}

// Version 2: repeats until it is between min and max. It doesn't copy the reading: it calls version 1
private static int readInt(Scanner sc, String message, int min, int max) {
    int value = readInt(sc, message);
    while (value < min || value > max) {
        System.out.println("Out of range (" + min + "-" + max + "): it doesn't count.");
        value = readInt(sc, message);
    }
    return value;
}

The version with a range has neither a print nor a nextInt of its own: it delegates to the simple one. If tomorrow the message needs another format, you change one line and both are fixed. And look at what happens with the 150: the version with a range rejects it inside its while, and playRound never finds out. That’s why the attempt is still 1/7.

playRound, the block that was copied three times in flow control:

private static int playRound(Scanner sc, int secret, int maxAttempts) {
    for (int n = 1; n <= maxAttempts; n++) {
        // readInt with a range doesn't let a 150 through: that attempt doesn't use up a round of the for
        int attempt = readInt(sc, "Attempt " + n + "/" + maxAttempts + ": ", 1, 100);
        if (guess == secret) {
            System.out.println("You got it!");
            return n;    // leaves the whole method, with the number of attempts
        }
        System.out.println(hint(guess, secret));
    }
    System.out.println("No attempts left. It was " + secret + ".");
    return -1;
}
nTypedguessRight?What it does
1150, 5050NoThe 150 is rejected in readInt; with 50, hint returns “Lower.”
22525No“Higher.”
33737No“Lower.”
43131Yes“You got it!” and return 4

In main, used = 4 and best goes from −1 to 4. The second game guesses at the first attempt, used = 1, and since 1 < 4, best becomes 1. When n is typed, the do-while ends and “Best game: 1 attempt” is printed. In the lost session, playRound uses up the for, prints “No attempts left” and returns −1; best stays at −1 and “You didn’t win any game.” is printed.

Why playRound returns an int and doesn’t print the final result. Because the one keeping track of the best game is main. If playRound only printed, main wouldn’t know how many attempts were used. −1 is a special value that means “didn’t guess”: no real number of attempts can be −1.

Why the condition for best has two parts. used != -1 discards the lost games, and best == -1 || used < best accepts the first win or one that beats the previous one. Without best == -1, the first win would never get in: 4 < −1 is false.

Why the secret is worked out once in main. new Random(42) with the same seed always gives the same sequence, but if you called nextInt on the same Random for every game, the second game would get another number (64, in fact). This way both games use 31 and the output can be repeated. For a real game, remove the seed: new Random().nextInt(100) + 1.

What if you check the range inside playRound with a continue instead of using readInt with a range?

The 150 would use up an attempt. In a for, continue jumps to the end of the iteration, and that’s where n++ runs, so after rejecting the 150 the program would ask for “Attempt 2/7”. With the same session (150, 50, 25, 37, 31), you’d guess right on attempt 5 instead of 4, and the statement says that a number out of range doesn’t use up an attempt. That’s why the repetition lives in readInt: its while keeps asking until it has a valid number, and the for in playRound doesn’t move on in the meantime.

Exam-style quiz

Now test yourself as in the exam. The FP2 Java quiz works like this: 15 questions in 15 minutes on the whole Java syllabus, single choice, multiple choice (wrong answers subtract), true or false, gap filling, matching, short answer and “what does this code print?”. Here are 11 original questions on methods in Java. Answer without running anything, press Check and read the explanation of each one. These questions are also the bank of the FP2 theory mock exam, which will mix them with those of the other Java topics.

Question 1Fill in the gaps

Fill in the header and body of a method that adds two integers:

public static ____ add(int a, int b) { ____ a + b; }. If a method returns nothing, you write ____ instead of the type.

Words:

  • void
  • def
  • yield
  • int
  • String
  • return
Solution

public static int add(int a, int b) { return a + b; }. If a method returns nothing, you write void instead of the type.

Before the name goes the return type: what return gives back. If it returns nothing, void. Java has no def: the header states the visibility, whether it’s static, the return type, the name and the parameters with their types.

Question 2Short answer

What does this program print?

public class Main {
    static void doubleIt(int x) {
        x = x * 2;
    }

    public static void main(String[] args) {
        int n = 5;
        doubleIt(n);
        System.out.println(n);
    }
}
Solution

Answer: 5

Java passes arguments by value: x receives a copy of 5. Doubling x doesn’t change n. If you wanted the result, the method would have to return it (return x * 2;) and you’d store it: n = doubleIt(n);.

Question 3Short answer

What does this program print?

public class Main {
    static void doubleIt(int[] v) {
        v[0] = v[0] * 2;
    }

    public static void main(String[] args) {
        int[] a = {5, 6};
        doubleIt(a);
        System.out.println(a[0] + a[1]);
    }
}
Solution

Answer: 16

Here a copy is passed too, but a copy of the reference: v and a point to the same array. Changing v[0] changes the array main sees: it becomes {10, 6} and 10 + 6 = 16.

Question 4Single choice

What does this program print?

public class Main {
    static String f(int x) { return "int "; }
    static String f(double x) { return "double "; }
    static String f(String x) { return "String"; }

    public static void main(String[] args) {
        System.out.println(f(3) + f(3.0) + f("3"));
    }
}
  1. int double String
  2. double double String
  3. int int String
  4. It doesn’t compile: there can’t be three methods f
Solution

Answer: int double String

Overloading allows several methods with the same name if the parameters differ. The compiler chooses which one to call from the argument types: 3 → int, 3.0 → double, "3" → String.

Question 5True or false

True or false?

  1. You can’t overload two methods that differ only in their return type.
  2. A static method can be called without creating objects, with ClassName.method().
  3. A method’s local variables still exist after the return.
  4. An int method with some path that never reaches a return doesn’t compile.
  5. In Java a parameter can have a default value, like def f(x=1) in Python.
Solution
  • T — You can’t overload two methods that differ only in their return type.
  • T — A static method can be called without creating objects, with ClassName.method().
  • F — A method’s local variables still exist after the return.
  • T — An int method with some path that never reaches a return doesn’t compile.
  • F — In Java a parameter can have a default value, like def f(x=1) in Python.

For the compiler, the signature is the name plus the parameter types; the return type doesn’t count, so two methods that only differ in that clash. Java has no default values: you simulate them with overloading (an f() that calls f(1)).

Question 6Short answer

What number does this program print?

public class Main {
    static int f(int n) {
        if (n <= 1) return 1;
        return n * f(n - 2);
    }

    public static void main(String[] args) {
        System.out.println(f(7));
    }
}
Solution

Answer: 105

f(7) = 7 · f(5) = 7 · 5 · f(3) = 7 · 5 · 3 · f(1), and f(1) is the base case, which returns 1. Total: 7 · 5 · 3 · 1 = 105. Each call waits on the stack for the next one to finish.

Question 7Single choice

What happens with this program?

public class Main {
    int twice(int x) {
        return 2 * x;
    }

    public static void main(String[] args) {
        System.out.println(twice(4));
    }
}
  1. It doesn’t compile: twice isn’t static and main has no object to call it on
  2. It prints 8
  3. It compiles but fails when run
  4. It prints 4
Solution

Answer: It doesn’t compile: twice isn’t static and main has no object to call it on

A method without static is an instance method: it needs an object (new Main().twice(4)). main is static, so it has no this. The fix in a simple program is to declare static int twice(int x).

Question 8Multiple · wrong ticks subtract

A class already has static int max(int a, int b). Which other methods can be added to the same class?

  1. static int max(int a, int b, int c)
  2. static double max(double a, double b)
  3. static int max(int[] v)
  4. static long max(int x, int y)
  5. static int max(int b, int a)
Solution

Answer: static int max(int a, int b, int c) · static double max(double a, double b) · static int max(int[] v)

The signature is the name + the parameter types (in order). Parameter names and the return type don’t change it, so those two versions would give method is already defined.

Question 9Short answer

What number does this program print?

public class Main {
    static int x = 10;

    static void change() {
        int x = 3;
        x++;
    }

    public static void main(String[] args) {
        change();
        System.out.println(x);
    }
}
Solution

Answer: 10

Inside change, int x = 3 declares a new local variable that hides the class one. The x++ changes that local, which disappears when the method ends. The field x is still 10.

Question 10Match

Match each term with its meaning:

Parameter
Argument
Signature
Return type
Overloading

Definitions:

  • Type of the value that return gives back
  • Several methods with the same name and different parameters
  • Name plus the parameter types
  • Inherited method redefined in a subclass
  • Variable in the header that receives a value
  • Value passed when calling the method
Solution
  • Parameter → Variable in the header that receives a value
  • Argument → Value passed when calling the method
  • Signature → Name plus the parameter types
  • Return type → Type of the value that return gives back
  • Overloading → Several methods with the same name and different parameters

In static int add(int a, int b), a and b are parameters; in add(2, 3), 2 and 3 are arguments. The leftover definition is overriding, which belongs to inheritance and isn’t the same as overloading.

Question 11Short answer

What number does this program print?

public class Main {
    static int count(String s, char c) {
        int n = 0;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == c) n++;
        return n;
    }

    public static void main(String[] args) {
        System.out.println(count("banana", 'a') * 10 + count("banana", 'n'));
    }
}
Solution

Answer: 32

«banana» has three as and two ns. The calls return 3 and 2, so 3 · 10 + 2 = 32. A method that returns a value can be used inside any expression.

Watch it step by step in Python Tutor

Let’s watch mistake 3 live. Open Python Tutor, choose Java, paste this program and step through with Next:

public class Demo {

    public static int doubleIt(int x) {
        x = x * 2;      // changes the COPY that lives in this frame
        return x;
    }

    public static void main(String[] args) {
        int n = 5;
        doubleIt(n);            // the 10 is calculated... and lost
        System.out.println(n);
        n = doubleIt(n);        // now the 10 is stored in n
        System.out.println(n);
    }
}

Output:

5
10

What to look at:

  1. In the first call, doubleIt(n), a frame appears with its own x = 5, a box different from main‘s n.
  2. The line x = x * 2 changes the frame’s x to 10. main‘s n is still 5.
  3. On return x, the frame disappears and the 10 goes back to main… where no variable is waiting for it. That’s why the first println writes 5.
  4. In the second call, n = doubleIt(n), the 10 that comes back is stored in n, and the second println writes 10.

Summary

  • A method that returns a value is good for calculating; if it prints inside, it’s only good for printing. When in doubt, let it return and let the caller print.
  • Every path of a method with a return type ends in return: the compiler doesn’t do the maths, it only checks that no path is left without a way out.
  • Arguments are passed by value: the method works with copies. If you want the result, n = method(n).
  • A special value (−1) lets a method that normally returns a number say “there was no result”.
  • Overloading allows one version to lean on another, without repeating code.
  • Without arrays you can keep maximums, minimums, sums and counters; to compare with something only known at the end, you’ll need to store them.
FP2 exam coming up?The pack for each exam, the Python and Java cheat sheet and the practical solutions with their tests, for free.See the pack

Cheat sheet: methods in Java

The essentials in 30 seconds

  • Header: visibility static type name(type param, …). While everything is in main‘s class, static.
  • With a return type: return value; on every path. With void: nothing, or return; to leave early.
  • Arguments are copied into the parameters in order. The only thing that leaves is the return: collect it.
  • Overloading: same name, different number or type of parameters. The return type doesn’t count.
  • return inside a loop leaves the whole method.

I want to…

I want to…CodeResult
A method that calculatesstatic double average(double a, double b) { return (a + b) / 2; }average(7, 8) → 7.5
A method that just does somethingstatic void greet(String n) { System.out.println("Hello, " + n); }Prints and returns nothing
Store what it returnsdouble m = average(7, 8);m is 7.5
Leave a void earlyif (value < 0) { return; }Ends without doing the rest
Answer yes or nostatic boolean isEven(int n) { return n % 2 == 0; }isEven(4) → true
Search and leave when foundfor (…) { if (found) return true; } return false;No break or flag
A “default value”static double fee(int c) { return fee(c, 15.20); }Calls the full version
Call another class’s methodGrades.classify(6.9)Class name, dot, method
Return “no result”return -1;The caller checks != -1

Templates from the exercises

Read and validate (exercise 2):

static int readTemperature(Scanner sc, int day) {
    int t;
    do {
        System.out.print("Day " + day + ": ");
        t = sc.nextInt();
    } while (t < -50 || t > 60);
    return t;
}

With 70 and then 27 → returns 27.

Maximum without storing the data (exercise 2): maximum = (day == 1) ? t : larger(maximum, t); → with 21, 24, 19, 27, 25, 18, 22 it ends at 27.

One version leaning on another (exercise 3):

static int readInt(Scanner sc, String msg, int min, int max) {
    int v = readInt(sc, msg);
    while (v < min || v > max) {
        v = readInt(sc, msg);
    }
    return v;
}

With 150 and then 50 → returns 50.

Most repeated errors

SymptomLikely cause
missing return statementA path (usually the last else if) ends without return
non-static method … cannot be referenced from a static contextThe method lacks static and you call it from main
incompatible types: unexpected return valuereturn value; in a void method
'void' type not allowed hereYou use a void method as if it returned something (inside println, in an assignment)
possible lossy conversion from double to intThe method promises int and returns a double
reference to … is ambiguousTwo overloaded versions fit equally well
method … is already definedTwo methods with the same name and the same parameters (only the return changes)
cannot find symbol with a variableYou’re trying to use a local variable of another method
The value doesn’t change after the callYou didn’t collect the return: n = doubleIt(n)
The average comes out without decimalsDivision between two int values: convert first with (double)

Before you submit, ask yourself

  • Does each method do a single thing, and does its name say which?
  • Do all the paths of my methods with a return type end in return?
  • Do I collect the value of every method that returns something?
  • Do the methods that calculate return the value instead of printing it?

That wraps up methods. The next topic is arrays in Java: the report card will be able to have as many subjects as you like, the week will be able to compare itself with its own average, and your methods will start receiving arrays… and being able to change them.

Keep goingAll Java articles

Did this article help you? Here is how you can support SergioLearns →

Ready for the exam?FP2 theory mock exam — Python, Java or the resit, against the clock and with your real mark (just like in the lab)