while
LoopThe while
statement in Java repeatedly runs code as long as the given condition remains true
.
int count = 0;while (count < 5) {System.out.println("Count is: " + count);count++;}
For
Loop in JavaThe for
loop repeats code over a range of values by initializing a variable, checking a condition, and updating the variable each iteration.
public class LoopExample {public static void main(String[] args) {for (int i = 0; i < 5; i++) {System.out.println("Iteration " + i);}}}/*Iteration 0Iteration 1Iteration 2Iteration 3Iteration 4*/
In Java, the for-each
statement allows you to directly loop through each item in an array or ArrayList
and perform some action with each item.
When creating a for-each
statement, you must include the for
keyword and two expressions inside of parentheses, separated by a colon. These include:
The handle for an element we’re currently iterating over.
The source array or ArrayList
we’re iterating over.
// array of numbersint[] numbers = {1, 2, 3, 4, 5};// for-each loop that prints each number in numbers// int num is the handle while numbers is the source arrayfor (int num : numbers) {System.out.println(num);}