while
As was introduced in Java Control Flow Statements, Java has the ability to loop repeatedly until some terminating condition is met. During each iteration of the loop, the same block of statements is executed. When the terminating condition evaluates to false, the loop ends and execution continues normally at the statement following the loop's closing curly brace.
There are three looping constructs in Java: while, do-while, and for. Every looping situation in Java can be handled with a while loop. Why does Java have a do-while and for loop if everything can be done with while? Some looping constructs are more cleanly and concisely written as do-while or for loops. In this tutorial we will look at while and do-while. We will take up the for loop in a later tutorial.
Before we look at examples of the while statement, let's take a look at its general form:
while(conditional_expression) {
statements_to_execute
}
This general form shows a simple while structure. As long as conditional_expression evaluates to true at the beginning of each loop, then statements_to_execute will continue to be executed. Notice that statements_to_execute is wrapped in curly braces {}. If statements_to_execute consists of a single statement only, the curly braces are optional. Most Java programmers consider it to be good coding style to always include the curly braces.
Warning: Unless you want a loop to continue forever, make sure that conditional_expression eventually evaluates to false in order to end the loop.
Let us look at some examples of while:
//Example 1
while(true) {
System.out.println("infinite loop");
}
//Example 2
int counter = 0;
while(counter < 5) {
System.out.println("iteration: " + counter);
counter++;
}
//Example 3
String args[] = {"red", "blue", "green"};
int counter = 0;
while(counter < args.length) {
System.out.println("Element " + counter + " is " + args[counter]);
counter++;
}
- In example 1 The while will loop forever. There are times when this is useful but in this case it just repeatedly prints out "infinite loop" until the JVM throws an exception.
- Example 2 shows a typical while loop. In this instance, an int variable named counter is initialized to 0. Next comes the while keyword and the conditional expression (counter <>
- Example 3 demonstrates another common use of loops--iterating over an array or collection and performing some action on each of the elements in the array or collection. Arrays and collections are just containers that can hold many variables (called elements). We will see more details on arrays and collections in upcoming tutorials. In this example an array of String objects is initialized with the values red, blue and green. These Strings are the array's elements. Next an int counter variable is initialized to 0. Then the while loop evaluates whether counter is less than the number of elements in the array (counter <>
Zero-based Counting
You may have noticed that all of my counter variables were initialized to 0 instead of 1. If I inserted a System.out.println("iteration: " + counter) into the code block, it would display "iteration: 0" for the first first pass through the loop, "iteration: 1" for the second pass, and so on. Java uses zero-based indexes for identifying the elements in arrays and collections. This means that the first element is 0, the second element is 1, and so on. Because looping over arrays and collections is the most common reason for using a while statement, it is more convenient to initialize the counter to match the first element in the array or collection. do-while
do is a Java language keyword that can be used in conjunction with while. When using the do-while construct, the block of statements wrapped in curly braces is executed before the conditional expression is evaluated. This means that the block of statements is always guaranteed to be executed at least once--during the first loop. This is the key difference between while and do-while. In a plain old while loop, the block of statements may never be executed if the conditional expression evaluates to false at the beginning of the first loop.
Let us look at an example of do-while:
int counter = 0;
do {
System.out.println("iteration: " + counter);
counter++;
}
while(counter != 5);
In this example an int variable named counter is initialized to 0. Next, the do's code block is executed the first time through. This prints out "iteration: 0" and increments counter by 1. Now the conditional expression is evaluated for the first time. Since counter does not equal 5, the do block is executed again. The code block is executed a total of 5 times until counter equals 5. At that point the while's conditional expression evaluates to false and the do-while loop breaks. Execution then continues normally at the statement following the do-while construct.
Here is a little program that pulls together some of what we have learned so far in the Java Programming Tutorial. This program accepts an operation (either ADD or MULTIPLY) and a list of at least two operands. It outputs the results of the calculation to standard out.
/* *
* @author Arunkumar Subramaniam
* FileName Calculator.java
* Date 01-DEC-2006
*/
public class Calculator {
public static final String ADD =
"ADD";
public static final String MULTIPLY =
"MULTIPLY";
private static final String USAGE =
"Usage: java Calculator [ADD MULTIPLY] oper1 oper2 ...";
private static final String INVALID_OPERATION =
"Error: You have not choosen a valid operation";
private static final String INVALID_ARGS =
"Error -- unexpected parameter list";
/**
* This is the entry point to a Java application. It is
* executed by the JVM.
*/
public static void main(String args[]) {
//ensure we have the appropriate number of arguments
if(null == args || args.length < 3) {
System.out.println(INVALID_ARGS);
System.out.println(USAGE);
System.exit(1);
}
//holds the operation (ADD or MULTIPLY)
String operationToPerform = "";
//holds the integers inputs
int operands[] = new int[args.length - 1];
int index = 0; //index is the loop counter
//loop through the input arguments and assign
//them to the appropriate variables
while(index < args.length) {
System.out.println(
"arg" + index + ":" + args[index]);
//the first element of the array is
//element 0. It holds the operationToPerform
if(index == 0) {
operationToPerform = args[index];
}
else {
//put the next String element out of the args array
String stringArg = args[index];
//convert the String to an int type
int toInt = Integer.parseInt(stringArg);
//place the int into the operands array
operands[index-1] = toInt;
}
//remember to increment the counter or the
//while loop will never end
index++;
}
//call calculate method and assign return
//value to output variable
int output = calculate(operationToPerform, operands);
//output the result
System.out.println(
"The result of " + operationToPerform +
" is " + output);
//exit and signal for the JVM to shutdown
System.exit(0);
}
/**
* Add or multiply an array of ints
*/
public static int calculate(
String operation,
int[] inputs) {
//convert operation to upper case to
//make comparisons case-insensitive
String op = operation.toUpperCase();
int counter = 0; //loop counter
int returnVal = -1; //will hold the result of the operation
//note: When comparing the equality of two
//objects, you should to use the
//equals method instead of the == operator
//either perform an ADD or MULTIPLY operation or print out an error message
if(ADD.equals(op)) {
returnVal = 0;
while(counter < inputs.length) {
returnVal += inputs[counter];
counter++;
}
}
else if(MULTIPLY.equals(op)) {
returnVal = 1;
while(counter < inputs.length) {
returnVal *= inputs[counter];
counter++;
}
}
else {
System.out.println(INVALID_OPERATION);
System.out.println(USAGE);
System.exit(1);
}
return returnVal;
}
}
To execute this program, first cut and paste it into a file named Calculator.java. Save it to a directory, for instance C:\source. In a DOS or shell window, change directory to the directory containing Calculator.java.
Compile Calculator.java into Java bytecode with the javac command.
C:\source>javac Calculator.java
If no errors were reported by javac, you should see a Java class file named Calculator.class in the directory.
Now start the JVM and and tell it what Java class contains the "public static void main (String args[])" method to execute.
C:\source>java Calculator ADD 1 1 1 1
You should see the output of adding 1 1 1 1. To review compiling and executing
0 comments:
Post a Comment