Single Choice Easy

QWhat will be the output of the following code snippet?

String[] fruits = {"Apple", null, "Banana"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

ID: #23060 Enhanced For Loop (For-Each Loop) in Java 110 views
Question Info
#23060Q ID
EasyDifficulty
Enhanced For Loop (For-Each Loop) in JavaTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A Apple, Banana
  • B Apple, null, Banana
  • C Apple, Exception
  • D null, Banana
Correct Answer

Explanation

Explanation: The output of the provided code snippet will be Apple, followed by null, and then Banana. In this example, an array of strings is defined, where one of the elements is null. When using the for-each loop to iterate through the fruits array, the loop processes each element sequentially. The first element, Apple, is printed as expected. Next, the loop encounters the null value, which is also printed; Java allows nulls to be output without throwing exceptions in this context. Finally, the loop prints Banana, the last element of the array. This behavior highlights the for-each loop's capability to handle null values gracefully, continuing to execute without interruption. It is essential for developers to be mindful of null values in arrays or collections when performing operations to avoid potential NullPointerExceptions during more complex processing scenarios. However, in simple output statements like this, nulls can be displayed without any issues. This demonstrates the flexibility of the for-each loop in traversing arrays containing optional or missing values without causing runtime errors.

Share This Question

Challenge a friend or share with your study group.