Using while and do

The other loop constructs in Java are provided by while and do. The general form of a while loop is as follows:

while( logical_test ){
   code block
}

The logical test is performed first. If the result is true, the code block is executed. If the result is false, the code block is skipped and execution continues after the closing brace. You can also combine a while test with an expression in a single statement, as follows:

while( i < ans.length() && ans.charAt( i ) != '*') i++ ;

If you want a loop that continues indefinitely, you can use a boolean literal value of true in the while statement like this:

while( true ){
  // code that repeats
}

The do loop construct moves the position of the logical test to the end of the code ...

Get Java 2™ Programmer Exam Cram™ 2 (Exam CX-310-035) now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.