Tutorial
Menus

Java Beginners - Java For Beginners

Java While & do while loop

Rating: 4.0/5 (1 vote cast)

Level   : Beginners
Author : Arunkumar S
Download Source : Not Avaliable

Java While & do while loop

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


< Previous 1 | 2 | 

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com