LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 17

Balance and history kept consistent Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;

class Wallet {
    private int balance;
    private final List<Integer> history = new ArrayList<>();

    boolean apply(int change) {
        if (balance + change < 0) return false;
        balance += change;
        history.add(change);
        return true;
    }

    int balance() { return balance; }
    int sumOfHistory() { return history.stream().mapToInt(Integer::intValue).sum(); }
}

public class Main {
    public static void main(String[] args) {
        Wallet w = new Wallet();
        int[] changes = {500, -200, -400, 100, -400};
        int ok = 0;
        for (int c : changes) if (w.apply(c)) ok++;
        System.out.println(ok + " " + w.balance() + " " + (w.balance() == w.sumOfHistory()));
    }
}
  • A 4 0 true Correct
  • B 5 -400 true
  • C 3 400 true
  • D 4 0 false
Correct Answer: Option A

Only -400 at a balance of 300 is refused. Because balance and history change together inside one method, they always agree.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links