While statement

The while statement provides looping of a statement or block of code so long as the condition expression evaluates to true:

// Read lines from a file:
in = new BufferedReader(new FileReader(“myfile.txt”));
try {
   String line = null;
   while ((line = in.readLine()) != null) { 
      System.out.println(“Read a line: “+line);
   }
} finally {
   in.close();
}

This example introduces a few advanced concepts, such as passing a newly constructed object in to a constructor and the use of a try-finally control block to clean up resources. The while loop conditional test first calls the readLine() method of the BufferedReader object, and assigns the value to the variable named line. The parenthesis that surround the “line = in.readLine()” phrase capture the value of this expression value that is returned by the sub-expression, and this is tested against the special null symbol. When the input reader runs out of lines it will return null and this will be assigned to the line variable. When line has a value of null, the test will fail, and the loop will exit. After the loop exist, the finally clause will be executed to close the input stream.