|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You use a whilestatement to continually execute a block of statements while a condition remains true. The general syntax of the
whilestatement is:First, thewhile (expression) { statement }whilestatement evaluates expression, which must return a boolean value. If the expression returnstrue, thewhilestatement executes the statement(s) in thewhileblock. Thewhilestatement continues testing the expression and executing its block until the expression returnsfalse.The following example program, called
WhileDemo, uses a
whilestatement (shown in boldface) to step through the characters of a string, appending each character from the string to the end of a string buffer until it encounters the letterg. You will learn more about theStringandStringBufferclasses in the next chapter, Object Basics and Simple Data Objects.
The value printed by the last line is:public class WhileDemo { public static void main(String[] args) { String copyFromMe = "Copy this string until you " + "encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i = 0; char c = copyFromMe.charAt(i); while (c != 'g') { copyToMe.append(c); c = copyFromMe.charAt(++i); } System.out.println(copyToMe); } }Copy this strin.The Java programming language provides another statement that is similar to the
whilestatement—the do-whilestatement. The general syntax of the
do-whileis:Instead of evaluating the expression at the top of the loop,do { statement(s) } while (expression);do-whileevaluates the expression at the bottom. Thus, the statements within the block associated with ado-whileare executed at least once.Here's the previous program rewritten to use
do-while(shown in boldface) and renamed toDoWhileDemo:
The value printed by the last line is:public class DoWhileDemo { public static void main(String[] args) { String copyFromMe = "Copy this string until you " + "encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i = 0; char c = copyFromMe.charAt(i); do { copyToMe.append(c); c = copyFromMe.charAt(++i); } while (c != 'g'); System.out.println(copyToMe); } }Copy this strin.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.