What are the for loop syntaxes in java?

10

Hello

Everyone programming in Java should already be tired of using for looping, which almost always has a syntax similar to this:

for (int x = 0; x < y; x++) {
    ...
}

I was analyzing some codes and came across a different syntax:

for (String novaString : arrayDeStrings) {
    ...
{ 

As I understand it, the loop will repeat X times, where X is equal to the array of strings ( arrayDeStrings.length ) and every repetition, novaString will receive the contents of one of the strings of arrayDeStrings .

Questions

Is this the same syntax that works? Are there any syntaxes other than those mentioned in this question? If so, how do they work?

    
asked by anonymous 31.03.2014 / 04:42

2 answers

14

This is a loop modality equivalent to for ... each of other languages.

As you suspected, it iterates through the arrayDeStrings array, sequentially picking up each of its items and returning it to novaString , executing the inner part of the loop with the value of each item respectively.

Imagine the following array of Strings :

String[] arrayDeStrings = { "Banana", "Maçã", "Pera" };

With this array, doing so much:

// Sintaxe foreach
for (String novaString : arrayDeStrings) {
   System.out.println( novaString );
}

how much:

// Sintaxe for com iterador
for (Iterator<String> i = arrayDeStrings.iterator(); i.hasNext(); ) {
   String novaString = i.next();
   System.out.println( novaString );
}

or so:

// Sintaxe for convencional
for(int i = 0; i < arrayDeStrings.length; i++) {
   System.out.println( arrayDeStrings[i] );
}

You'll get the expected result:

Banana
Maçã
Pera
  

Note that foreach is just a syntax-sugar , as per the relevant comment @mgibsonbr , it will be transformed into one of the two codes that were exposed next, depending on whether it is an Iterable or Array in the parameter. >

    
31.03.2014 / 04:46
3

This type of construction started with Java 5. It is called for-each and does exactly this: for each element given in the loop of for , it executes one or more commands.

Reading the code becomes easier, and internally it compiles to the same bytecodes as the for or the corresponding while would do.

It can be used in arrays , Collections and any other construct that implements an Iterable interface.

There are situations where you can not use this for :

  • To update Array values: it only reads the array values, you can not use this for to update its values. For example, the code below is invalid :
for (String novaString : arrayDeStrings) {     
 novaString = "banana";     
}
  • to traverse two structures at the same time: for traverses only one structure. There is no construct of this for that allows you to traverse two arrays by comparing their values, for example.
01.04.2014 / 14:53