Take the 2-minute tour ×

Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as


but why is my variant is not working? Any help would be appreciated.

char[][] array = new char[x][y];
for (char[] row : array)
    for (char element : row)
        element = '~';
share|improve this question
add comment

4 Answers

up vote 7 down vote accepted

From the Sun Java Docs:

So when should you use the for-each loop?

Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.

share|improve this answer
So, with iterator it would work? Thank you for answer. –  Shark Apr 14 '10 at 9:37
@Shark: arrays don't provide an iterator (unless you wrap them using Arrays.asList()), but a normal old-school for-loop works just fine. –  Joachim Sauer Apr 14 '10 at 9:51
add comment

Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:

    char[][] array = new char[10][10];
    for (char[] row : array)
        Arrays.fill(row, '~');
share|improve this answer
Thank you for the hint :) –  Shark Apr 14 '10 at 14:14
Thank you for the hint –  SHiRKiT Jul 25 '12 at 0:14
add comment

This is because the element char is not a pointer to the memory location inside the array, it is a copy of the character, so changing it will only change the copy. So you can only use this form when referring to arrays and objects (not simple types).

share|improve this answer
add comment

The assignment merely alters the local variable element.

share|improve this answer
add comment

Your Answer


