LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Exercise 2 of 4

Records, Enums and Sealed Classes Predict the Output

  • 20 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Read each Java program and choose what it prints. Every program was compiled and run on Java 21, so the answers are the real output.

Question 11 Medium

What is the output of the following Java program?

Main.java
import java.util.HashMap;
import java.util.Map;

record Seat(char row, int no) { }

public class Main {
    public static void main(String[] args) {
        Map<Seat, String> booked = new HashMap<>();
        booked.put(new Seat('B', 4), "Asha");
        booked.put(new Seat('C', 1), "Ravi");
        booked.put(new Seat('B', 4), "Meena");
        System.out.println(booked.size() + " " + booked.get(new Seat('B', 4)) + " " + booked.containsKey(new Seat('A', 1)));
    }
}
A 2 Meena false
B 3 Asha false
C 2 Asha false
D 3 Meena true
Question page & discussion
Question 12 Medium

What is the output of the following Java program?

Main.java
sealed interface Expr permits Num, Add, Mul { }
record Num(int value) implements Expr { }
record Add(Expr l, Expr r) implements Expr { }
record Mul(Expr l, Expr r) implements Expr { }

public class Main {
    static int eval(Expr e) {
        return switch (e) {
            case Num n -> n.value();
            case Add a -> eval(a.l()) + eval(a.r());
            case Mul m -> eval(m.l()) * eval(m.r());
        };
    }

    public static void main(String[] args) {
        Expr e = new Add(new Num(2), new Mul(new Num(3), new Add(new Num(4), new Num(1))));
        System.out.println(eval(e) + " " + eval(new Mul(new Num(6), new Num(7))));
    }
}
A 17 42
B 25 42
C 15 42
D Compilation error
Question page & discussion
Question 13 Hard

What is the output of the following Java program?

Main.java
sealed interface Txn permits Credit, Debit { }
record Credit(String acc, int amount) implements Txn { }
record Debit(String acc, int amount) implements Txn { }

public class Main {
    static String classify(Txn t) {
        return switch (t) {
            case Credit(String acc, int amt) when amt >= 10000 -> "large credit to " + acc;
            case Credit(var acc, var amt) -> "credit " + amt;
            case Debit(var acc, var amt) when amt > 5000 -> "flag debit " + amt;
            case Debit d -> "debit " + d.amount();
        };
    }

    public static void main(String[] args) {
        Txn[] ts = {new Credit("A1", 15000), new Debit("A1", 7000), new Credit("B2", 500), new Debit("B2", 300)};
        for (Txn t : ts) System.out.println(classify(t));
    }
}
A large credit to A1 flag debit 7000 credit 500 debit 300
B credit 15000 debit 7000 credit 500 debit 300
C large credit to A1 debit 7000 credit 500 debit 300
D Compilation error
Question page & discussion
Question 14 Medium

What is the output of the following Java program?

Main.java
sealed abstract class Account permits Savings, Current {
    abstract double rate();
}
final class Savings extends Account { double rate() { return 3.5; } }
non-sealed class Current extends Account { double rate() { return 0; } }
class BusinessCurrent extends Current { @Override double rate() { return 0.5; } }   // allowed: Current is non-sealed

public class Main {
    static String kind(Account a) {
        return switch (a) {
            case Savings s -> "savings";
            case Current c -> c.getClass().getSimpleName().toLowerCase();
        };
    }

    public static void main(String[] args) {
        Account[] accs = {new Savings(), new Current(), new BusinessCurrent()};
        for (Account a : accs) System.out.print(kind(a) + ":" + a.rate() + " ");
        System.out.println();
    }
}
A savings:3.5 current:0.0 businesscurrent:0.5
B savings:3.5 current:0.0 current:0.0
C savings:3.5 current:0.0 current:0.5
D Compilation error
Question page & discussion
Question 15 Medium

What is the output of the following Java program?

Main.java
import java.util.List;

interface Priced { int price(); }

enum Size implements Priced {
    SMALL(150), MEDIUM(220), LARGE(290);
    private final int p;
    Size(int p) { this.p = p; }
    public int price() { return p; }
}

enum Extra implements Priced {
    CHEESE { public int price() { return 40; } },
    OLIVES { public int price() { return 30; } };
}

public class Main {
    public static void main(String[] args) {
        List<Priced> order = List.of(Size.LARGE, Extra.CHEESE, Extra.CHEESE, Extra.OLIVES);
        int total = order.stream().mapToInt(Priced::price).sum();
        System.out.println(total + " " + order);
    }
}
A 400 [LARGE, CHEESE, CHEESE, OLIVES]
B 390 [LARGE, CHEESE, OLIVES]
C 400 [Size.LARGE, Extra.CHEESE, Extra.CHEESE, Extra.OLIVES]
D Compilation error
Question page & discussion
Question 16 Medium

What is the output of the following Java program?

Main.java
import java.util.EnumSet;

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

public class Main {
    public static void main(String[] args) {
        EnumSet<Day> work = EnumSet.range(Day.MON, Day.FRI);
        EnumSet<Day> weekend = EnumSet.complementOf(work);
        EnumSet<Day> gym = EnumSet.of(Day.SUN, Day.TUE, Day.THU);
        EnumSet<Day> gymOnWorkdays = EnumSet.copyOf(gym);
        gymOnWorkdays.retainAll(work);
        System.out.println(weekend + " " + gym + " " + gymOnWorkdays + " " + work.size());
    }
}
A [SAT, SUN] [TUE, THU, SUN] [TUE, THU] 5
B [SAT, SUN] [SUN, TUE, THU] [TUE, THU] 5
C [SUN, SAT] [TUE, THU, SUN] [TUE, THU] 5
D [SAT, SUN] [TUE, THU, SUN] [TUE, THU, SUN] 5
Question page & discussion
Question 17 Medium

What is the output of the following Java program?

Main.java
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        record Score(String name, int total) { }                 // local record: visible only here
        List<String> raw = List.of("Asha:45,40", "Ravi:30,38", "Meena:48,47");
        Score best = raw.stream()
            .map(s -> s.split(":"))
            .map(p -> new Score(p[0], List.of(p[1].split(",")).stream().mapToInt(Integer::parseInt).sum()))
            .max(Comparator.comparingInt(Score::total))
            .orElseThrow();
        System.out.println(best + " " + best.total());
    }
}
A Score[name=Meena, total=95] 95
B Score[name=Asha, total=85] 85
C Meena 95
D Compilation error
Question page & discussion
Question 18 Medium

What is the output of the following Java program?

Main.java
enum IdGenerator {
    INSTANCE;
    private long next = 1000;
    synchronized long nextId() { return ++next; }
}

public class Main {
    public static void main(String[] args) {
        IdGenerator a = IdGenerator.INSTANCE, b = IdGenerator.valueOf("INSTANCE");
        System.out.println(a.nextId() + " " + b.nextId() + " " + (a == b) + " " + IdGenerator.values().length);
    }
}
A 1001 1002 true 1
B 1001 1001 false 1
C 1000 1001 true 1
D 1001 1002 false 2
Question page & discussion
Question 19 Medium

What is the output of the following Java program?

Main.java
import java.util.List;

record Page<T>(List<T> items, int page, int totalPages) {
    boolean hasNext() { return page < totalPages; }
    <R> Page<R> map(java.util.function.Function<T, R> f) { return new Page<>(items.stream().map(f).toList(), page, totalPages); }
}

public class Main {
    public static void main(String[] args) {
        Page<String> p = new Page<>(List.of("java", "go"), 1, 3);
        Page<Integer> lengths = p.map(String::length);
        System.out.println(p.hasNext() + " " + lengths + " " + new Page<>(List.of(), 3, 3).hasNext());
    }
}
A true Page[items=[4, 2], page=1, totalPages=3] false
B false Page[items=[4, 2], page=1, totalPages=3] false
C true Page[items=[java, go], page=1, totalPages=3] false
D Compilation error
Question page & discussion
Question 20 Hard

What is the output of the following Java program?

Main.java
record Address(String city, String pin) { }
record Customer(String name, Address address) { }

public class Main {
    static String region(Object o) {
        return switch (o) {
            case Customer(var name, Address(var city, var pin)) when pin.startsWith("4") -> name + " (west, " + city + ")";
            case Customer(var name, Address(var city, var pin)) when pin.startsWith("1") -> name + " (north, " + city + ")";
            case Customer(var name, Address a) -> name + " (other)";
            default -> "not a customer";
        };
    }

    public static void main(String[] args) {
        System.out.println(region(new Customer("Asha", new Address("Pune", "411001"))));
        System.out.println(region(new Customer("Ravi", new Address("Delhi", "110001"))));
        System.out.println(region(new Customer("Meena", new Address("Chennai", "600001"))));
        System.out.println(region(42));
    }
}
A Asha (west, Pune) Ravi (north, Delhi) Meena (other) not a customer
B Asha (other) Ravi (other) Meena (other) not a customer
C Asha (west, Pune) Ravi (north, Delhi) Meena (west, Chennai) not a customer
D Compilation error
Question page & discussion
Up next · Exercise 3Find the Error10 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links