Java Arena
Step 1 of 7

Methods that return a value

In module 17 the methods of your classes did something: they printed, or they changed the object's instance variables. They were all void. An object's method can also return a value, just like the methods of module 11. This basket counts its fruit:

Main.java
public class Main {
    public static void main(String[] args) {
        Basket basket = new Basket();
        System.out.println(basket.isEmpty());
        basket.addApples(3);
        basket.addPears(2);
        int fruit = basket.total();
        System.out.println("Fruit in the basket: " + fruit);
        System.out.println(basket.isEmpty());
    }
}
Basket.java
public class Basket {
    private int apples;
    private int pears;

    public Basket() {
        this.apples = 0;
        this.pears = 0;
    }

    public void addApples(int count) {
        this.apples = this.apples + count;
    }

    public void addPears(int count) {
        this.pears = this.pears + count;
    }

    public int total() {
        return this.apples + this.pears;
    }

    public boolean isEmpty() {
        return this.apples + this.pears == 0;
    }
}
Output
true
Fruit in the basket: 5
false
  • public int total() returns an int: the apples and pears of this basket added up. There's no static in the header, because the method belongs to an object and works with that object's own variables.
  • In main, the call basket.total() stands for the value it returns. Here main stores it in fruit, but the call can go anywhere a value can: in a print line, a calculation or a comparison.
  • isEmpty() returns a boolean, so its call works as a condition on its own: if (basket.isEmpty()) { ... }. A method that answers a yes-or-no question usually has a name that starts with is or has, such as isEmpty or hasRoom.

You've used methods like these on lists and strings: list.size() returns how many values a list has, and word.isEmpty() tells whether a string is empty. Now your own classes can have them too.

Why return the value instead of printing it? For the same reason as in module 11: the caller decides what to do with it. main can compare the totals of two baskets, add them up, or print them in its own words.

Your task

Challenge 1 of 3

The Scoreboard keeps the points of a home team and an away team. Add a method totalPoints() that returns the points of both teams together. The check gives the home team 3 and 1 points and the away team 2, and prints what totalPoints() returns:

6

Challenge 2

Add a method leader() to the Scoreboard. It returns the String home when the home team has more points, away when the away team has more, and tie when they have the same. The check asks at the start, after 2 points for the away team, and after 3 more for the home team:

tie
away
home

Challenge 3

What does this program print? The water is in milliliters, and a cup is 250 of them.