Java development for beginners 8. While statement

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

while (expression) {
     statement(s)
}
  

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

You can implement an infinite loop using the while statement as follows:

while (true){
    // your code goes here
}

 

The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
     statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

You can see how the while statement works with the two examples of code below, explained in the video tutorial:

package com.edu4java.tutorial8;

public class Tutorial8 {
public static void main(String[] args) {
	int meter=2;
	while (meter<=5) {
		System.out.println(meter);
//		meter=meter+1;
		meter++;
	}
}
}

package com.edu4java.tutorial8;

import java.util.Scanner;

public class Tutorial8_1 {
	public static void main(String[] args) {
		System.out.println("Program to add several numbers");
		Scanner scanner = new Scanner(System.in);
		int collector = 0;
		int newNumber = 0;
		while (newNumber >= 0) {
			System.out.println("Insert new number to add or -1 to end");
			newNumber = scanner.nextInt();
			if (newNumber > 0) {
				collector = collector + newNumber;
			}
		}
		System.out.println("Total: " + collector);
	}
}
<< Previous Next >>