Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int sum = 0;
for (int x : a) {
x = x * 10;
sum = sum + x;
}
System.out.println(a[0] + " " + sum);
}
}1 60
- Expecting
10 60: the for-each variable holds a copy of the element, sox = x * 10changes the copy and the array stays{1, 2, 3}. - Expecting a compile error: the for-each variable is not read-only; assigning to it compiles, but the change never reaches the array.
- How would you rewrite the loop so that it multiplies every element of the array by 10?
- What would change if the loop header were
for (final int x : a)?