LearnFrenzy
Sign in Take a free test

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

A compact constructor that normalises values Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
record Username(String value) {
    Username {
        value = value.strip().toLowerCase();
        if (value.length() < 3) throw new IllegalArgumentException("too short: '" + value + "'");
    }
}

public class Main {
    public static void main(String[] args) {
        Username a = new Username("  AshaK ");
        String r;
        try { new Username(" Al "); r = "ok"; } catch (IllegalArgumentException e) { r = e.getMessage(); }
        System.out.println(a.value() + " " + a.equals(new Username("ashak")) + " " + r);
    }
}
  • A ashak true too short: 'al' Correct
  • B AshaK false too short: 'Al'
  • C ashak false ok
  • D AshaK true too short: 'al'
Correct Answer: Option A

The compact constructor rewrites the parameter, and that final value is what gets stored.

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