nerdexam
Oracle

1Z0-803 · Question #155

Given: public class Test3 { public static void main(String[] args) { double[] array = {10, 20.23, 'c', 300.00f}; for (double d : array) { d = d + 10; System.out.print(d + " "); } } } What is the resul

The correct answer is A. 20.0 30.23 109.0 310.0. The code initializes a double array using a mix of primitive literal types, which Java's widening primitive conversion automatically casts to double. It then iterates through this array, increments a local loop variable by 10 for each element, and prints the result.

Working with Java Data Types

Question

Given:

public class Test3 { public static void main(String[] args) { double[] array = {10, 20.23, 'c', 300.00f}; for (double d : array) { d = d + 10; System.out.print(d + " "); } } } What is the result?

Options

  • A20.0 30.23 109.0 310.0
  • B20.0 30.23 c10 310.0
  • CCompilation fails.
  • DAn exception is thrown at runtime.

How the community answered

(18 responses)
  • A
    72% (13)
  • B
    6% (1)
  • C
    6% (1)
  • D
    17% (3)

Why each option

The code initializes a `double` array using a mix of primitive literal types, which Java's widening primitive conversion automatically casts to `double`. It then iterates through this array, increments a local loop variable by 10 for each element, and prints the result.

A20.0 30.23 109.0 310.0Correct

During array initialization, Java performs widening primitive conversions: `10` (int) becomes `10.0`, `'c'` (char) becomes its ASCII value `99.0`, and `300.00f` (float) becomes `300.0`. The enhanced for loop assigns a copy of each array element's value to the local `d` variable. Adding 10 to these `d` values produces `20.0`, `30.23`, `109.0`, and `310.0` respectively, which are then printed.

B20.0 30.23 c10 310.0

This option incorrectly assumes that the `char` 'c' would be treated as a character literal during arithmetic, resulting in string concatenation 'c10', rather than being converted to its numeric ASCII value (99.0) before addition.

CCompilation fails.

Compilation does not fail because all literal types provided (`int`, `double`, `char`, `float`) can be implicitly converted to `double` through widening primitive conversion, which is a safe operation.

DAn exception is thrown at runtime.

An exception is not thrown at runtime because all array initialization and arithmetic operations are valid due to Java's automatic type conversions and the use of primitive types.

Concept tested: Java primitive type widening, enhanced for-loop with primitives

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Topics

#primitive type conversions#for-each loop#char to double conversion

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice