Multiple choice java

String[] elements = {
 "for",
 "tea",
 "too"
};
String first = (elements.length > 0) ? elements[0] : null;

What is the result?

  1. Compilation fails

  2. An exception is thrown at runtime

  3. The variable first is set to null

  4. The variable first is set to elements[0]

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

The array has 3 elements, so elements.length > 0 is true. The ternary operator returns elements[0] which is 'for'. Option A and B are incorrect because there's no compilation error or exception. Option C is incorrect because first is not set to null.

AI explanation

The ternary operator (elements.length > 0) ? elements[0] : null evaluates the condition first: since the array has 3 elements, elements.length > 0 is true, so the expression evaluates to elements[0], and first is assigned that value ("for"). No exception or compile error occurs because the array is non-empty and properly initialized.