Java While & Do-While loop

  1. Syntax
  2. While Loop in Java
  3. Do While Loop in Java
  4. While & Do-While Differentiation

Note
Here I am using,
OS : Linux (Ubuntu 12.04)
IDE : Eclipse Tool
Eclipse : Juno (Version 4.2.0)
Package : Default package

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<n) {
			
			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<n);
	}
}
 
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






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com