Loops
For loops
In Java, you can use for loops to execute a block of code repeatedly for a fixed number of times. Here's an example:
In the above example, we use a for loop to print the numbers from 1 to 5. The loop starts with an initial value of i
equal to 1, and executes as long as i
is less than or equal to 5. The loop increments i
by 1 after each iteration, using the i++
shorthand for i = i + 1
.
You can also use it for loops with arrays, like this:
In the above example, we use a for loop to iterate over an array of numbers. The loop starts with an initial value of i
equal to 0, and executes as long as i
is less than the length of the numbers
array. The loop increments i
by 1 after each iteration.
While loops
In Java, you can use while loops to execute a block of code repeatedly as long as a certain condition is true. Here's an example:
In the above example, we use a while loop to print the numbers from 1 to 5. The loop starts with an initial value of i
equal to 1, and executes as long as i
is less than or equal to 5. The loop increments i
by 1 after each iteration.
You can also use while loops with boolean variables, like this:
In the above example, we use a while loop to print the numbers from 1 to 5, but we use a boolean variable keepGoing
to control the loop instead of a numeric condition. The loop starts with an initial value of keepGoing
equal to true
, and executes as long as keepGoing
is true
. The loop sets keepGoing
to false
when i
equals 5, causing the loop to exit.
Do-while loops
In Java, you can use do-while loops to execute a block of code repeatedly at least once, and then as long as a certain condition is true. Here's an example:
In the above example, we use a do-while loop to print the numbers from 1 to 5. The loop starts by executing the block of code once and then continues to execute as long as i
is less than or equal to 5. The loop increments i
by 1 after each iteration.
Do-while loops are useful when you need to execute a block of code at least once, regardless of the condition.
That's an overview of loops, while loops, and do-while loops in Java.
Last updated