-
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
Lecture1.6
-
Lecture1.7
-
Lecture1.8
-
Lecture1.9
-
Lecture1.10
-
Lecture1.11
-
Lecture1.12
-
Lecture1.13
-
Lecture1.14
-
Java Loop Control
There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms.
1. While Loop
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean_expression) {
//Statements
}
When executing, if the boolean expression result is true then the actions inside the loop will be executed. This will continue as long as the expression result is true.
[php]
public class ForLoopExample {
public static void main(String args[]) {
int a = 1;
while( a < 10 ) {
System.out.println("value of a : " + a );
a++;
}
}
}
[/php]
2. Do-While Loop
The DO … WHILE loop is almost similar to the WHILE loop, the difference is that in this loop, the execution of statements occur before checking of a condition.
Syntax:
do {
//Statements
}while(Boolean_expression);
do…while loop checks the value of the loop control variable at the bottom of the loop after one repetition has occurred.
[php]
public class DoWhileLoop {
public static void main(String[] args) {
int i =10;
do{
i=i+10;
System.out.println("Loop Counter Variable=" +i);
}while (i<10);
}
}
[/php]
3. For Loop
For Loop checks the condition and executes the set of the statements , It is loop control statement in java. It contain the following statements such as “Initialization”
, “Condition”
and “Increment/Decrement”
statement
Syntax:
for(initialization; Condition; update)
{
//Statements
}
[php]
public class ForLoopExample{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println("Hello");
}
}
}
[/php]