Print Page Print Page

CH8 – Creating Arrays

  1. Create a new class named CreateArrays. Add a method to it named tryArrays. Create two arrays of integers and initialize them the following two different ways.
  2. Add a main method that calls tryArrays.
public class CreateArrays {
  public static void tryArrays(){
    int[] countsA;
    countsA = new int[4];
    int[] countsB = {1,2,3,4};

    countsA[0] = 1;
    countsA[1] = 2;
    countsA[2] = 3;
    countsA[3] = 4;

    for(int i = 0; i < countsA.length; i++)
    {
      System.out.println("countsA: " + countsA[i] + " countsB: " + countsB[i]);
    }
  }
  public static void main(String[] args){
    CreateArrays.tryArrays();
  }
}
  1. Save, compile, and run the program.
$ javac CreateArrays.java
$ java CreateArrays
countsA: 1 countsB: 1
countsA: 2 countsB: 2
countsA: 3 countsB: 3
countsA: 4 countsB: 4