LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 15

Changing the loop variable in a for-each loop Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        for (int x : a) x *= 10;
        System.out.print(Arrays.toString(a) + " ");
        for (int i = 0; i < a.length; i++) a[i] *= 10;
        System.out.println(Arrays.toString(a));
    }
}
  • A [1, 2, 3] [10, 20, 30] Correct
  • B [10, 20, 30] [100, 200, 300]
  • C [1, 2, 3] [1, 2, 3]
  • D [10, 20, 30] [10, 20, 30]
Correct Answer: Option A

The for-each variable is a copy of each element; only the index loop changes the array.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links