1Z0-803 · Question #109
Given: 1. public class Simple { 2. public float price; 3. public static void main (String [] args) { 4. Simple price = new Simple(); 5. price = 4; 6. } 7. } Which will make this code compile and run?
The correct answer is B. Change line 5 to:. The given code attempts to assign an integer literal to an object reference variable, leading to a compile-time type mismatch error.
Question
Options
- AChange line 5 to:
- BChange line 5 to:
- CChange line 5 to:
- DChange line 5 to:
- EThe code compiles and runs properly; no changes are necessary.
How the community answered
(21 responses)- A5% (1)
- B76% (16)
- C14% (3)
- D5% (1)
Why each option
The given code attempts to assign an integer literal to an object reference variable, leading to a compile-time type mismatch error.
(Assuming Option B changes line 5 to `price.price = 4;` or `price.price = 4.0f;`) This correction properly assigns the numeric value to the `price` field of the `Simple` object, which is of type float, resolving the type mismatch; the integer `4` is implicitly widened to a float.
The code, as written with `price = 4;`, will not compile because an `int` literal cannot be directly assigned to an object reference variable of type `Simple`.
Concept tested: Variable shadowing, field access, type conversion
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Topics
Community Discussion
No community discussion yet for this question.