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.
A. Syntax
While
while(condition) {
// Statement if the condition is true..
}
Do While
do {
// Do Statement at least once and then check condition..
} while(condition);
B. While Loop in Java
While_Ex1.java
public class While_Ex1 {
int i = 1;
void check(int n) {
while(i
System.out.println("While - i : " + i);
i++;
}
}
}
class MainClass {
public static void main(String args[]) {
While_Ex1 obj = new While_Ex1();
obj.check(4);
}
}
Sample Output
While - i : 1
While - i : 2
While - i : 3
C. Do While Loop in Java
DoWhile_Ex1.java
public class DoWhile_Ex1 {
int i = 1;
void check(int n) {
do {
System.out.println("Do While - i : " + i);
i++;
} while(i
}
}
class MainClass {
public static void main(String args[]) {
DoWhile_Ex1 obj = new DoWhile_Ex1();
obj.check(4);
}
}
Sample Output
Do While - i : 1
Do While - i : 2
Do While - i : 3
D. While & Do-While Differentiation
While_Ex2.java
public class While_Ex2 {
int i = 1;
void check1(int n) {
while(i < n) {
System.out.println("While - i : " + i);
}
}
void check2(int n) {
do {
System.out.println("Do While - i : " + i);
} while(i < n);
}
}
class MainClass {
public static void main(String args[]) {
While_Ex2 obj = new While_Ex2();
obj.check1(1);
obj.check2(1);
}
}
Sample Output
Do While - i : 1
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.