LearnFrenzy
Sign in Take a free test

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

Which overloaded constructor is chosen? Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Value {
    String kind;
    Value(int x) { kind = "int"; }
    Value(long x) { kind = "long"; }
    Value(double x) { kind = "double"; }
    Value(Object x) { kind = "Object"; }
}

public class Main {
    public static void main(String[] args) {
        byte b = 1;
        System.out.println(new Value(b).kind + " " + new Value(5L).kind + " " + new Value(2.5f).kind + " " + new Value("s").kind + " " + new Value('A').kind);
    }
}
  • A int long double Object int Correct
  • B Object long double Object Object
  • C int long Object Object int
  • D int int double Object Object
Correct Answer: Option A

Constructor overloads are resolved like method overloads: widening (byte→int, float→double, char→int) is preferred over boxing.

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