Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Constructors

What will be the output of the following code?

class Box {
    int width, height;
    Box() {
        width = 10;
        height = 10;
    }
    Box(int w, int h) {
        width = w;
        height = h;
    }
    void display() {
        System.out.println(width + "," + height);
    }
}

public class Test {
    public static void main(String[] args) {
        Box b1 = new Box();
        Box b2 = new Box(5, 15);
        b1.display();
        b2.display();
    }
}
A10,10 5,15
B5,15 10,10
C10,10 10,10
DCompilation error due to constructor overloading
Step-by-Step Solution
Solution:
  1. Step 1: Identify which constructors are called

    b1 uses the no-argument constructor setting width and height to 10. b2 uses the two-parameter constructor setting width=5 and height=15.
  2. Step 2: Understand display output

    b1.display() prints "10,10" and b2.display() prints "5,15" on separate lines.
  3. Final Answer:

    10,10 5,15 -> Option A
  4. Quick Check:

    Constructor sets values correctly, output matches [OK]
Quick Trick: Match constructor parameters to object creation [OK]
Common Mistakes:
  • Assuming default constructor sets zero values
  • Mixing order of printed outputs
  • Thinking overloading causes errors here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes