Arrays in Java

Objectives

  • Use arrays in Java
  • Use multidimensional arrays

Arrays

  • declare array: int[] num;
  • create array: num = new int[15];
  • combine declaration and creation: int[] num = new int[15];
  • declare, create, and initialize: int[] num = { 5, 7, 1, 3, 1 };
  • can make array of objects: String[] names = new String[8];
  • getting the length of an array: num.length
  • pass to methods by just using name: Arrays.sort(num);
  • receive in a method using "datatype[] arrayname"
  • arrays passed by reference, so methods can change contents of arrays passed to them
  • you can create and initialize anonymous arrays (good for passing as arguments to methods): new String[]{"abc", "def"}
  • typical loop through array: "for (int i=0; i<arrayname.length; i++)"
  • can use new for loop to iterate through array: "for ( var : arrayname )"
  • see numerous array examples on the CIS 160 demonstration programs page
  • System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
  • Arrays class

Multidimensional arrays

  • a two dimensional array in Java is basically an array of one dimensional arrays
  • creating a variable that can reference a two dimensional array:
    int[][] arr;
  • creating a two dimensional array:
    arr = new int[2][3];
  • you can combine creating the variable with creating the array:
    int[][] arr = new int[2][3];
  • you can combine initialization with creation:
    int[][] arr = { {1, 2, 3}, {4, 5, 6} };
    where arr[0][0] is 1, arr[0][1] is 2, ..., and arr[1][2] is 6
  • since each row of a multidimensional array is an array, the arrays in different rows can be different sizes:
    int[][] arr = { {1, 2, 3}, {4, 5} };
  • you can use each row of a multidimensional as a regular array (the following code treats the 4th row of arr[][] as a regular array:
    for (i=0; i<arr[3].length; i++)
  • individual rows of an array can be created independently:
    int[][] c = new int[2];
    c[0] = new int[3];
    c[1] = new int[2];
  • see MultiDim1.java: multidimensional array demonstration