Using a Variable 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

Answer:

stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0
stuff[4] has 0

Using a Variable as an Index

The index of an array is always an integer type. It can be a literal, or an expression that evaluates to an integer. For example, the following are legal:

int values[] = new int[7];
int index;

values[ 6 ] = 42;           // literal

index  = 0;
values[ index ] = 71;       // put 71 into cell 0

index  = 5;
values[ index ] = 23;       // put 23 into cell 5

index  = 3;
values[ 2+2 ] = values[ index-3 ];  // same as values[ 4 ] = values[ 0 ];

QUESTION 8:

Given the above declarations, is the following legal?

index = 4;
values[ index+2 ] = values[ index-1 ];