LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 6

Assigning to the for-each variable Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 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[] nums = {1, 2, 3};
        for (int n : nums) n = n * 100;
        String[] words = {"a", "b"};
        for (String w : words) w = w.toUpperCase();
        System.out.println(Arrays.toString(nums) + " " + Arrays.toString(words));
    }
}
  • A [1, 2, 3] [a, b] Correct
  • B [100, 200, 300] [A, B]
  • C [100, 200, 300] [a, b]
  • D [1, 2, 3] [A, B]
Correct Answer: Option A

The loop variable is a copy of each element (for objects, a copy of the reference). Reassigning it does not change 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