Loops in Java
Loops in Java
• Consider your daily routine, you wake up, you brush, you wear clothes and then
head off to work, come back, eat and then sleep off. Again, the next day, you do
the same things in the same order and go to sleep again. This cycle keeps on
repeating. This concept of repetitive actions performed time and again is called a
loop.
• Looping in Java is defined as performing some lines of code in an ordered fashion
until a condition is false.
• The condition is important because we do not want the loop to be running forever.
1. Simple for Loop
2. Java Nested for loop
3. For-each or Enhanced for Loop
Simple for Loop
• Java for loop consists of 3 primary factors which define the loop itself.
• These are the initialization statement, a testing condition, an increment or
decrement part for incrementing/decrementing the control variable.
Nested for Loop
• If we have a for loop inside another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.
for-each Loop
• The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true.
• As soon as the Boolean condition becomes false, the loop automatically stops.
• The while loop is considered as a repeating if statement.
• If the number of iteration is not fixed, it is recommended to use the while loop.
• Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
do-while Loop
• The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true.
• If the number of iteration is not fixed and you must have to execute the loop at least
once, it is recommended to use a do-while loop.
• Java do-while loop is called an exit control loop.
• Therefore, unlike while loop and for loop, the do-while check the condition at the
end of loop body.
• The Java do-while loop is executed at least once because condition is checked after
loop body.
Java If-else Statement
• if statement
• if-else statement
Break Statement