Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Java Loops

javaloop

Uploaded by

omier2084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Loops

javaloop

Uploaded by

omier2084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java loops

loops
Loops
• Loops can execute a block of code as long as the specified condition is
reached.
• Loops are handy because they save time, reduce errors, and they
make code more readable.
While Loop
• The while loop exute through a block of code as long as a specified
condition is true:
• Syntax
Example
• while (condition) { int i = 0;
• // code block to be executed while (i < 5) {
•} System.out.println(i);
i++;
}
The Do/While Loop
• The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true.
• Syntax Example
do { int i = 0;
do {
// code block to be executed System.out.println(i);
} i++;
while (condition); }
while (i < 5);
Java For Loop
• When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop.
Syntax Example
• for (statement 1; statement 2; statement 3) { for (int i = 0; i <= 10; i = i + 2)
{
// code block to be executed System.out.println(i);
} }
Java Break and Continue
• The break statement can also be used to jump out of a loop.
• This example jumps out of the loop when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Java Continue
• The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
• Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}

You might also like