Basic JAVA 8
Loop in Java
There is main 3 type of loops in java.
for loop
while loop
do while loop
1. for Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loop in java.
Simple for loop
for-each or Enhanced for loop
Labeled for loop
1) Simple for loop
The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.
Syntax:
for( initialization; condition; incr/decr ) {
//code to be executed }
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
2) for-each loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for( Type var : array ) {
//code to be executed
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
3) Infinitive For loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for( ; ; ) {
//code to be executed
}
Example:
public class ForExample {
public static void main(String[] args) {
for(;;){
System.out.println("infinitive loop");
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
.....
ctrl+c
Now, you need to press ctrl+c to exit from the program.
2. while Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
while( condition ) {
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=5){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
3. do while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use while loop.
It is executed at least once because condition is checked after loop body.
do
{
//code to be executed
} while( condition );
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )