"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The for-each style for loop

The for-each style for loop

Published on 2024-08-21
Browse:880

Purpose: The for-each loop is used to sequentially traverse the elements of an array or collection, from beginning to end.

Syntax:

for(tipo var-iter : conjunto) {
  // bloco de instruções
}

Operation: At each iteration, the next element of the array is assigned to the iteration variable, which must have a type compatible with the elements of the array.

Advantages:

  • Eliminates the need for a loop counter.
  • Avoids the need to manually define loop limits.
  • Reduces the chance of errors related to the array index.

Limitations:
The iteration variable is read-only, meaning it cannot be used to change the underlying array.
The loop loops through all elements of the array unless a break statement is used to exit the loop early.

Example of Limitation:
Even changing the iteration variable within the loop, this does not affect the original array:

for(int x : nums) {
  x = x * 10; // Sem efeito no array original
}

Use with Arrays and Collections: The for-each loop can also be used to cycle through elements of other collections in Java, in addition to arrays, such as those provided by the Collections Framework.

O laço for de estilo for-each

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/o-laco-for-de-estilo-for-each-2kjk?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3