When looping through collections, you can use enhanced loops:
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println(item);
}
Answer from Abdulgood89 on Stack OverflowIs there a shorter way to write a for loop in Java? - Stack Overflow
foreach - What is the syntax of the enhanced for loop in Java? - Stack Overflow
ELI5: Understanding For Loops in Java
What makes for-loops difficult for beginners?
When should I use a for loop versus a while loop in Java?
What is the difference between a while loop and a do-while loop in Java?
How many types of loops are there in Java?
Videos
Enhanced for loop:
for (String element : array) {
// rest of code handling current element
}
Traditional for loop equivalent:
for (int i=0; i < array.length; i++) {
String element = array[i];
// rest of code handling current element
}
Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html
An enhanced for loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
As the title said, can you guys help me understand the for loops in java like I'm five. I've been trying to learn java but when it comes to for loop, I'm having a hard time understanding it. Especially when my professor is using single letters like for int i, x, y, and such something like that. Whenever I'm coding, I always use proper names so I don't get confused with the variables. But I still get confused using for loops;-; so I mostly prefer using the do.. while or while loops. But I want to learn to understand it because I noticed my prof always uses it and as well as ytber programmers.