Using an Expression as an Index

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
index = 4;
values[ index+2 ] = values[ index-1 ];

Answer:

Yes.

Using an Expression as an Index

Using an expression for an array index is a very powerful tool. You often solve a problem by organizing the data into arrays, and then processing that data in a systematic way using variables as indexes. Here is a further example:

class ArrayEg2
{
  public static void main ( String[] args )
  {
    double[] val = new double[4];  // an array of double 
                                   // cells initialized to 0.0
    val[0] = 0.12;
    val[1] = 1.43;
    val[2] = 2.98;

    int j = 3;
    System.out.println( "cell 3: " + val[ j   ] );
    System.out.println( "cell 2: " + val[ j-1 ] );

    j = j-2;
    System.out.println( "cell 1: " + val[ j   ] );
   }
}

You can, of course, copy this program to your editor, save it and run it. Arrays can get confusing. Playing around with a simple program now will pay off later.

QUESTION 9:

What does the above program output?

cell 3:
cell 2:
cell 1: