Array Initialization

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
int[] scores = new double[25];

Answer:

  • scores[ 0 ]       OK
  • scores[ 1 ]       OK
  • scores[ -1 ]       illegal
  • scores[ 10]       OK
  • scores[ 25 ]       illegal
  • scores[ 24 ]       OK

Array Initialization

Lacking any other information, the cells of an array are initialized to the default value for their type. Each cell of a numeric array is initialized to zero. Each cell of an array of object references is initialized to null.

Of course, the program can assign values to cells after the array has been constructed. In the following, the array object is constructed and each cell is initialized to 0. Then some assignment statements explicitly change some cells:

class ArrayEg1
{
  public static void main ( String[] args )
  {
    int[] stuff = new int[5];

    stuff[0] = 23;
    stuff[1] = 38;
    stuff[2] = 7*2;

    System.out.println("stuff[0] has " + stuff[0] );
    System.out.println("stuff[1] has " + stuff[1] );
    System.out.println("stuff[2] has " + stuff[2] );
    System.out.println("stuff[3] has " + stuff[3] );
    System.out.println("stuff[4] has " + stuff[4] );
  }
}

QUESTION 7:

What does the program write?

stuff[0] has
stuff[1] has
stuff[2] has
stuff[3] has
stuff[4] has