Java While Loop Program
Java While Loop Program
program
http://freepdf-books.com
Java while loop is used to execute
statement(s) until a condition holds true. In
this tutorial we will learn looping using Java
while loop examples. First of all lets discuss
while loop syntax:
while (condition(s)) {
// Body of loop
}
http://freepdf-books.com
is considered true and zero is considered
false.
http://freepdf-books.com
Following program asks the user to input an
integer and prints it until user enter 0
(zero).
import java.util.Scanner;
class WhileLoop {
public static void main(String[] args) {
int n;
System.out.println("Out of loop");
}
}
http://freepdf-books.com
Output of program:
class WhileLoop {
public static void main(String[] args) {
int n;
http://freepdf-books.com
System.out.println("Input an integer");
}
}
}
class BreakWhileLoop {
public static void main(String[] args) {
int n;
while (true) {
System.out.println("Input an integer");
n = input.nextInt();
if (n == 0) {
break;
}
System.out.println("You entered " + n);
}
}
}
class BreakContinueWhileLoop {
public static void main(String[] args) {
int n;
http://freepdf-books.com
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Input an integer");
n = input.nextInt();
if (n != 0) {
System.out.println("You entered " + n);
continue;
}
else {
break;
}
}
}
}
http://freepdf-books.com