go to previous page   go to home page   go to next page

Answer:

The filled blanks are seen below.


Avoiding null

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" );
}

In this example, any cell of the array might reference a String (depending on what happened previously in the program) so all cells must be visited. Cells that contain null are handled differently that those that refer to Strings.

(Actually, println() will print "null" when given a null reference, so the if statement is not really required. But sometimes things go horribly wrong if you send a method a a null parameter, so it is wise to test for it.)


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?


go to previous page   go to home page   go to next page