Question 19
Back to Exercise
What is the output of the following Java program?
record Marks(String subject, int score) {
Marks { // compact constructor: validation
if (score < 0 || score > 100) throw new IllegalArgumentException("score " + score);
subject = subject.toUpperCase();
}
}
public class Main {
public static void main(String[] args) {
Marks m = new Marks("maths", 92);
String r;
try { new Marks("art", 120); r = "created"; } catch (IllegalArgumentException e) { r = e.getMessage(); }
System.out.println(m.subject() + " " + m.score() + " " + m + " " + r);
}
}
- A MATHS 92 Marks[subject=MATHS, score=92] score 120 Correct
- B maths 92 Marks[subject=maths, score=92] created
- C MATHS 92 Marks@1b6d score 120
- D Compilation error
Correct Answer: Option A
A record keeps its fields private and final; the compact constructor validates and normalises them before they are assigned.
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!