LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 6

Counting with an EnumMap Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.EnumMap;
import java.util.Map;

enum Mode { UPI, CARD, CASH, WALLET }

public class Main {
    public static void main(String[] args) {
        Map<Mode, Integer> amount = new EnumMap<>(Mode.class);
        String[][] txns = {{"CASH", "200"}, {"UPI", "450"}, {"WALLET", "99"}, {"UPI", "1200"}, {"CASH", "80"}};
        for (String[] t : txns) amount.merge(Mode.valueOf(t[0]), Integer.parseInt(t[1]), Integer::sum);
        System.out.println(amount + " " + amount.containsKey(Mode.CARD));
    }
}
  • A {UPI=1650, CASH=280, WALLET=99} false Correct
  • B {CASH=280, UPI=1650, WALLET=99} false
  • C {UPI=1650, CARD=0, CASH=280, WALLET=99} true
  • D {UPI=1650, CASH=280, WALLET=99} true
Correct Answer: Option A

EnumMap iterates in declaration order and contains only keys that were put.

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