Run-time Array Length

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 two lines:

      data  = scan.nextInt();
      array[ index ] = data ;

can be replaced by the single line:

       array[ index ] = scan.nextInt();

And then the declaration int data; should be removed.

Run-time Array Length

An array object is constructed as the program runs (as are all objects). When an array is constructed, its size can be in a variable. Here is the previous example, with some modifications:

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array;
    int   data;
    Scanner scan = new Scanner( System.in );

    // determine the size and construct the array
    System.out.print( "What length is the array? " );
    int size  = scan.nextInt();

    array     = new int[  ]; 

    // input the data
    for ( int index=0; index < array.length; index++)
    {
      System.out.print( "enter an integer: " );
      array[ index ] = scan.nextInt();
    }
      
    // write out the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
}      

QUESTION 6:

Fill in the blank.