LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 16

A constructor that throws Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Percentage {
    static int created = 0;
    final int value;
    Percentage(int v) {
        if (v < 0 || v > 100) throw new IllegalArgumentException("out of range: " + v);
        value = v;
        created++;
    }
}

public class Main {
    public static void main(String[] args) {
        Percentage p = new Percentage(40);
        try {
            p = new Percentage(140);
        } catch (IllegalArgumentException e) {
            System.out.print(e.getMessage() + " | ");
        }
        System.out.println(p.value + " " + Percentage.created);
    }
}
  • A out of range: 140 | 40 1 Correct
  • B out of range: 140 | 140 2
  • C out of range: 140 | 0 1
  • D 40 1
Correct Answer: Option A

The failing new never returns, so p keeps the old object and created was not incremented.

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