I have this loop
String str = "123";
byte[] bytes = str.getBytes();
for (byte b : bytes) { System.out.println(b);
}
//output: 49 50 11 (ASCII for 1 2 3)
My question is, how does b
increment?
I have this loop
String str = "123";
byte[] bytes = str.getBytes();
for (byte b : bytes) { System.out.println(b);
}
//output: 49 50 11 (ASCII for 1 2 3)
My question is, how does b
increment?
The JLS guarantees that this loop is equivalent to
for (int n = 0; n < bytes.length; ++n){
byte b = bytes[n];
System.out.println(b);
}
i.e. you can guarantee that the traversal is from the start to the end of the array. As you can see, the foreach loop syntax is clearer although at the expense, in this case, of obscuring the order of element traversal.
Have a look here:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
For-each loop iterate through the whole collection.
It is a short version of the for
loop with iterator.
This is called an enhanced for loop
It just syntactic sugar for the normal iterative for loop you think of.
for(int i = 0; i < bytes.length; i++){
System.out.println( bytes[i] );
}
This is a foreach
-loop.
b
is an element out of the array bytes
the loop will take every element in the array.
Therefore b will not increment.
This is known as the enhanced for-loop
It is used for Collections and Arrays. It is used when you want to iterate through the entire collection or array.
bytes
is an array, and the compiler knows this. It also knows that it can get the length of the array by saying bytes.length
. So under the covers it generates the obvious loop, somthing like:
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
}