Master the for
keyword in Java through comprehensive examples. Explore its usage and unlock the potential of efficient looping in Java programming.
Print the numbers 0 to 4:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
The for
loop loops through a block of code a number of times.
From the example above:
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
The following example outputs all elements in the cars array, using a "for-each" loop:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
#java