aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enhansed For Loop Please explain me Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enhansed For Loop Please explain me" Watch "Enhansed For Loop Please explain me" New topic
Author

Enhansed For Loop Please explain me

Ami Ambre
Ranch Hand

Joined: Dec 26, 2007
Posts: 58
int [][]i={{1,2,3},{4,5,6}};
for (int []n: i)
/*This is single dimensional Array so how can you are accessing multi dimensional Arrays within Single dimensional Array.*/

for(int n2: i[2])
// what is this?
Jamie MacDonald
Greenhorn

Joined: May 17, 2008
Posts: 20
The enhanced for loop is in the form of
for( declaration : expression ) { }
where
declaration declares a new variable (which typically will be used in the for loop)
and
expression must evaluate to an array of the type of the variable declared in declaration

In your first example, n is declared as a single dimensional array and the expression is a two dimensional array--which is an array of single dimensional arrays--so this meets the enhanced for loop specification.

In the second example, the expression "i[2]" is a single dimensional int array and n2 is an int, so again you are fine as far as the compiler is concerned. You will however get a runtime exception (ArrayIndexOutOfBoundsException) since i is only of length 2 (contains 2 int arrays) and therefore the maximum array index is 1.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Enhansed For Loop Please explain me
 
Similar Threads
Sierra Bates SCJP 6 Ch. 3 No. 3
Array conversion Question from Dan's test
Doubt in Array Declaration
multidimensional arrrays
Two dimensional Array (Strange thing)