nerdexam
Oracle

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.

Working with Java Data Types

Question

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?

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)
  • A
    5% (1)
  • B
    76% (16)
  • C
    14% (3)
  • D
    5% (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.

AChange line 5 to:
BChange line 5 to:Correct

(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.

CChange line 5 to:
DChange line 5 to:
EThe code compiles and runs properly; no changes are necessary.

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

#variable scope#shadowing#primitive assignment#object fields

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice