Avoid ArrayIndexOutOfBoundsException

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:

if ( args.length != 3 || !args[1].toUpperCase().equals("TO") )
{
  System.out.println("java CopyBytes source to destination");
  return;
}

Avoid ArrayIndexOutOfBoundsException

The above is the only correct answer, given the choices. The args.length != 3 must come first. If it is true, then the short-circuit OR immediately evaluates to true and there is no danger of trying to look at a non-existent args[1].

If the order were reversed (or if a non-short-circuit OR where used), then the if might throw an ArrayIndexOutOfBoundsException.

QUESTION 21:

Does this code protect the user against accidentally reversing the order of the source and the destination file?