This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes enhanced for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "enhanced for " Watch "enhanced for " New topic

enhanced for

venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
why cant we use enhanced for loop for two dimensional variables??? please explain

venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
Oops.. am sorry, i meant,

why cant i get the output for this program where i have used two dimen array,
my output was,
(which made me think that i cant use 2d here..)
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

The issue isn't so much with the enhanced for loop; its the System.out.println() call with an array as the parameter. This is resulting in an implicit call to the toString() method on an array. As such, you do not get the contents of the array output. Even if you do this outside of a for loop, you'd get something similar. For example, the code:

would output something like:

To print out the contents of the array, we need to use a utility method in the java.util.Arrays class (notice the plural Arrays). In particular, we can use one of the overloaded toString() methods:

This would result in the output:
[1, 2, 3]

So you can change your code to

And that will output the each of the arrays. So you'd get:

[5, 3, 2]
[4, 3, 2]

And if you want to iterate through the "sub-array" you can out a seconffor loop inside the first for loop:

This would output:


Does that help?
[ August 15, 2008: Message edited by: Mark Vedder ]
venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
yeah.. really it does.
Thank Mark
I agree. Here's the link:
subject: enhanced for
It's not a secret anymore!