Single Choice Easy

QWhat will happen if you try to modify the elements of an array while using a for-each loop in Java?

ID: #23055 Enhanced For Loop (For-Each Loop) in Java 78 views
Question Info
#23055Q 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 The program will compile successfully but may throw a runtime exception.
  • B The elements will be modified without any issues.
  • C The loop will stop executing.
  • D You cannot modify elements in a for-each loop.
Correct Answer

Explanation

In Java, the for-each loop is designed for iteration without allowing direct modification of the elements being processed. When using the for-each loop, the variable that represents the current element is effectively a copy of the element in the array or collection, meaning that any changes made to this variable do not affect the original element. If you attempt to assign a new value to the loop variable, it will not modify the actual element in the collection; rather, it will only change the local copy. For instance, if you execute for (int num : numbers) { num = num * 2; }, the original numbers array remains unchanged. This design encourages immutability and functional programming principles, promoting better coding practices. If you need to modify elements during iteration, you should consider using a traditional for loop, where you have direct access to the index of each element, allowing you to update them as necessary. Alternatively, you can create a new collection that contains the modified values based on the original collection. This characteristic makes the for-each loop suitable for scenarios where you want to perform read-only operations without affecting the data.

Share This Question

Challenge a friend or share with your study group.