Friday Java Quiz: Enhanced for Loop
Q: Will the following program compile? Run without exceptions? If so, what will it print?
public class Foo {
public static void main(String[] args) {
String[][] sss = new String[2][];
int c = 0;
for (String[] ss: sss) {
ss = new String[3];
for (String s: ss) {
s = "Slot # " + c++;
}
}
for (String[] ss: sss) {
for (String s: ss) {
System.out.println(s);
}
}
}
}
Strict rules this week: you must not actually compile the program before answering the questions.
Re: Friday Java Quiz: Enhanced for Loop
You are trying to override the temporary variable ss and s provided by the "foreach" construct.
Therefore the content of the array is always null and never updated, since it does not act like a referenced variable like suggested by the foreach construct.
So the first part must be written using good old for..loop with array indexes like this:
for(int i = 0; i < sss.length; i++){
sss[i] = new String[3];
for(int j = 0; j < sss[i].length; j++){
sss[i][j] = "Slot # " + c++;
}
}
Then, the second foreach will work as expected.
Enjoy! :)