What is better for or for each? Why? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

What is better for or for each? Why?

2nd May 2018, 4:23 AM
Sa√ļl Acatzin L√≥pez Roque
Sa√ļl Acatzin L√≥pez Roque - avatar
2 Respuestas
+ 9
for is better for usual iterative operations which have initialization, condition and incrememt/decrement. foreach is better for working with arrays. Please note that Java doesn't have foreach, it's called enhanced for loop.
2nd May 2018, 5:17 AM
DAB - avatar
+ 2
As stated in D A B 's response for is good for iterative operations such as a count. The foreach, or enhanced for loop, is useful for iteration through collections. Things like traversing through directories and files.
2nd May 2018, 6:51 AM
Josh Schweigert
Josh Schweigert - avatar