Avoiding null

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:

The filled blanks are seen below.

Avoiding null

In this example, any cell of the array might reference a String so all cells must be visited. To make the output look nice, cells that contain null are handled differently that those that refer to Strings.

String[] strArray = new String[8] ;  // combined statement

. . . . .
for (int j=0; j < strArray.length; j++ )
{
  if ( strArray[j] != null )
    System.out.println( "cell " + j + ": " + strArray[j] );
  else
    System.out.println( "cell " + j + ": " + "empty" );
}

(Actually, println() will print "null" when given a null reference, so the if statement is not really required. But with some methods things will go horribly wrong if you send them a null.)

QUESTION 7:

Inspect this code:

for (int j=0; j < strArray.length; j++ )
  System.out.println( "The string " + strArray[j] + " is " +
      strArray[j].length() + " characters long." );

Is this program likely to work?