CH8 – Accessing Elements

  1. Create a new Java class named AccessingElements.
  2. Add a main method with the following code.
public class AccessingElements{
  public static void main(String[] args){
    int counts[] = new int[4];
    int i = 0;
    while(i < 4){
      System.out.println(counts[i]);
      i++;
    }
  }
}
  1. Compile and run the program. The program prints four zeros.
$ javac AccessingElements.java
$ java AccessingElements
0
0
0
0
  1. Add the following code after the array creation but before the declaration of the i variable.
counts[0] = 7;
counts[1] = counts[0]*2;
counts[2]++;
counts[3] -= 60;
  1. Compile and run the program.
$ javac AccessingElements.java
$ java AccessingElements
7
14
1
-60

The complete program should appear as follows.

public class AccessingElements{
  public static void main(String[] args){
    int counts[] = new int[4];
    counts[0] = 7;
    counts[1] = counts[0]*2;
    counts[2]++;
    counts[3] -= 60;
    int i = 0;
    while(i < 4){
      System.out.println(counts[i]);
      i++;
    }
  }
}