0

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?

  • 1
    To answer your question quickly: the foreach java loop is just a convenience. Behind the scenes it uses Iterators – Colin D Mar 12 '14 at 16:13

6 Answers6

3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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.

Jakub H
  • 2,130
  • 9
  • 16
0

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] );

}
Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152
0

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.

maximus_de
  • 382
  • 1
  • 3
  • 12
0

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.

See The Java Tutorials

Brian
  • 7,098
  • 15
  • 56
  • 73
0

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];
}
Hot Licks
  • 47,103
  • 17
  • 93
  • 151