Q: What will happen if you try to modify the elements of an array while using a for-each loop in Java?
-
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.
D
Answer:
D
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.
Related Topic:
Share Above MCQ