<< James Gosling: It Really Should Be JDK 7 | Home | Neal Gafter To Join Microsoft >>

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.

Tags :


Re: Friday Java Quiz: Enhanced for Loop

Good one. It won't compile. ss and s are implicitly final.

Re: Friday Java Quiz: Enhanced for Loop

I vote for a NullPointerException in the second part of the program. Since we are not modifying really the array, we have an array of nulls, through which the inner loop will try to iterate. So NullPointerException.

Re: Friday Java Quiz: Enhanced for Loop

Doh. I was wrong. At least you know I follow the rules. ;-) What I was thinking of is that you *can* use final with an enhanced for loop (while you obviously can't with a classic for loop).

Re: Friday Java Quiz: Enhanced for Loop

i think nothing, ArrayList is by default Object[8] and when you iterate by empty list you get nothing.

Re: Friday Java Quiz: Enhanced for Loop

Java does not pass by reference, so the asignment on line 6 may or may not write through to the underlying array. (An array is not an Iterable, so some wrapper code must be present.) So, a NullPointerException?

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! :)

Re: Friday Java Quiz: Enhanced for Loop

I think that code will work. String is immutable Object. Because it is a object, assignment gives reference not bit value. One can do anything with object. So first loop initialization is correct. So second loop will work perfectly.

Re: Friday Java Quiz: Enhanced for Loop

I guessed: Slot #0 Slot #1 Slot #2 Slot #3 Slot #4 Slot #5 I was wrong!

Re: Friday Java Quiz: Enhanced for Loop

I agree with David, the code would compile, but you would get a NPE, when you run it.

Add a comment Send a TrackBack