Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q5 of 15
Java - Constructors

What will be the output of this code snippet?

class Point {
int x, y;
Point() { x = 0; y = 0; }
Point(int x, int y) { this.x = x; this.y = y; }
void display() { System.out.println(x + "," + y); }
}
public class Test {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(3, 4);
p1.display();
p2.display();
}
}
A0,0 0,0
B3,4 0,0
CCompilation error
D0,0 3,4
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor assignments

    p1 uses no-arg constructor setting x=0,y=0; p2 uses two-arg constructor setting x=3,y=4.
  2. Step 2: Output from display method

    p1.display() prints "0,0" and p2.display() prints "3,4" in that order.
  3. Final Answer:

    0,0 3,4 -> Option D
  4. Quick Check:

    Constructor sets fields correctly [OK]
Quick Trick: Constructor parameters initialize object fields [OK]
Common Mistakes:
  • Mixing order of outputs
  • Assuming default values for p2
  • Expecting compilation error due to overloading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes