C-style Input Loop

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

No. The line terminating characters may be different in the copy. Sometimes this is a useful feature if you often copy text files between different types of computer.

C-style Input Loop

Here is the loop from the copyFile() method.

  line = source.readLine();
  while ( line != null )
  {
   dest.write(line);
   dest.newLine();
   line = source.readLine();
  }

Here is the same loop written in a style that is commonly used with the "C" programming language. This style also works for Java:

  while ( (line = source.readLine()) != null )
  {
   dest.write(line);
   dest.newLine();
  }

The key to understanding this is to understand that an assignment statement is an expression and has a value. That value is the value that is assigned to the variable. So this:

(line = source.readLine())

has a value that is non-null after a successful readLine() and null upon end-of-file. Say that the file has data in it:

C-style loop

This may be more bother than it is worth, but programmers familiar with C are likely to use this style, so you will see it often.

QUESTION 14:

Will this form of the loop work correctly with an empty file?