1Z0-803 · Question #135
Given: class X { String str = "default"; int ivalue = 17; X(String s) { str = s; } X(int i) { ivalue = i; } void print() { System.out.println(str + " " + ivalue); } public static void main(String[] ar
The correct answer is C. hello 17. This question evaluates understanding of Java constructor overloading, the order of instance variable initialization, and how these interact with constructor logic during object creation.
Question
Given:
class X { String str = "default"; int ivalue = 17; X(String s) { str = s; } X(int i) { ivalue = i; } void print() { System.out.println(str + " " + ivalue); } public static void main(String[] args) { new X("hello").print(); new X(92).print(); } } What is the result?
Options
- Adefault 17
- Bhello 92
- Chello 17
- Ddefault 92
How the community answered
(30 responses)- A10% (3)
- B7% (2)
- C80% (24)
- D3% (1)
Why each option
This question evaluates understanding of Java constructor overloading, the order of instance variable initialization, and how these interact with constructor logic during object creation.
This would be the output if the constructor `X(String s)` did not modify `str` from its default initial value, which is incorrect.
This result implies that a single constructor call sets both `str` to "hello" and `ivalue` to 92, which is not possible with the provided overloaded constructors as each handles only one type of parameter.
When `new X("hello")` is called, the instance variables `str` and `ivalue` are first initialized to "default" and 17, respectively. Then, the `X(String s)` constructor sets `str` to "hello", while `ivalue` remains its initial value of 17 because it is not modified by this constructor.
This would be the result of the second call `new X(92).print()`, where `str` remains "default" and `ivalue` is set to 92. The correct answer pertains to the first `print()` call.
Concept tested: Java constructor overloading and instance initialization order
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Topics
Community Discussion
No community discussion yet for this question.