CH8 – Displaying Arrays

  1. Create a new Java class named DisplayingArrays.
  2. Add a main method and add the following code.
public class DisplayingArrays{
  public static void main(String[] args){
    int[] a = {1,2,3,4};
    System.out.println(a);
  }
}
  1. Compile and run the program. The array’s address is printed.
$ javac DisplayingArrays.java 
$ java DisplayingArrays
[I@6d06d69c
  1. Add a method named printArray to the class and add a method call as the last line of main.
public class DisplayingArrays{
  public static void main(String[] args){
    int[] a = {1,2,3,4};
    System.out.println(a);
    printArray(a);
  }
  public static void printArray(int[] a){
    System.out.print("{" + a[0]);
    for(int i = 1; i< a.length;i++){
      System.out.print(","+a[i]);
    }
    System.out.println("}");
  }
}
  1. Compile and run the program.
$ javac DisplayingArrays.java 
$ java DisplayingArrays
[I@6d06d69c
{1,2,3,4}