04. Java Arrays

Java Arrays

  • Unlike C/C++, when you declare an array variable, there are no array elements allocated for that variable. Instead, a Java array variable is declared as only a reference (pointer) to an array.

Syntax to declare a one-dimensional array variable:

type-or-class-id var-ID [] ; OR type-or-class-id [ ] var-ID;

  • Optional modifiers if class-scope ONLY (before type or class-id): public, private, protected, synchronized (discussed in next chapter notes)
  • Note: unlike C/C++, DO NOT PUT A NUMBER IN THE SQUARE BRACKETS TO SPECIFY DIMENSION)
  • After declaring an array (without assigning), the array variable refers to null if a class-scope variable (uninitialized if method-scope). You must assign memory allocated for an array to an array variable.

To allocate memory for an array, use the new operator: new type[array-size]Example:

intNums = new int[50]; //array size may be a variable
int max = 256;
chs = new char[max];

Unlike C/C++, you may get the number of elements allocated for an array: arrayName.length for example, intNums.length

Enhanced For Loops

Using the Enhanced for loop: (NEW with JDK 1.5!)

Syntax: for(elementType varName: arrayName) - varName will have the value of the next element each iteration of the loop

/*

Exercise 4.1: Write a static method that allocates memory for numElems floats (where numElems is an int parameter) AND initializes each element to a float value (another parameter) multiplied by its index, then return the array in a return statement. Write another static method that displays the array backwards (the ONLY parameter MUST be the array, nothing else)! In main, declare an array of floats variable, call the first method passing 8 and 10.0 (assign to the main array variable), then call the 2nd method passing the array variable.

*/
public class Exercise_4_1
{
    public static void main(String[] args)
    {
        float mainArray[];
        mainArray = CreateArray(8, (float) (10.0));  // Why need typecast for 10.0 to float ??
        PrintArray(mainArray);
    }
   
    public static float [] CreateArray(int numElems, float f_elementMultiplier)
    {
        float f_functionArray[];
        f_functionArray = new float[numElems];
        for(int i=1; i < f_functionArray.length; i++)
            f_functionArray[i] = i * f_elementMultiplier;  // Use multiplier & assign value to each element of an array
        return f_functionArray;
    }
   
    public static void PrintArray(float functionArray[])
    {
        for(float i:functionArray)
            System.out.println(i);
    }
}

Multidimensional Arrays

To declare multi-dimensional array variables: Add another [ ] for each dimension in the variable declaration, for example:

char [][] chMatrix;  
byte [][][] byte3Dim;

To allocate memory for the elements, indicate the size of each dimension in additional [ ], or in the initialization with nested { } for each dimension, for example:

chMatrix = new char[100][20]; // using the declarations from above
byte3Dim = { // allocates a 3 X 4 X 2
  { {1, 2}, {3, 4}, {5, 6}, {7, 8} },
  { {9, 10}, {11, 12}, {13, 14}, {15, 16} },
  { {17, 18}, {19, 20}, {21, 22}, {23, 24} } };

To reference elements, add another set of [ ] with the index of the dimension, for example: chMatrix[i][j] = 'A';// in nested for loops

where i and j must be between 0 and its dimension size-1.

To find the size of each dimension, use the length variable for that dimension, for example:

for(int i=0 ; i < b3D.length ; ++i ) 
   for(int j=0 ; j < b3D[i].length ; ++j )
      for(int k=0; k < b3D[i][j].length; ++k ) // etc.

/* Exercise 4.2: Declare a two-dimensional array of ints in main.

    Write a static method to read in the size of each dimension, allocate memory for the array and return it. 
    Write another static method to initialize each element to the sum of its indices (for example, the element at 3, 4 would have the value 7). Call those methods in main.
 */
import java.util.Scanner;
public class Exercise_4_2
{
    public static void main(String[] args)
    {
        int [][] iArrayTwoDim;
        iArrayTwoDim = CreateTwoDimArray();       // read in the size of each dimension, allocate memory for the array
        InitWithSumOfIndices(iArrayTwoDim);       // initialize each element to the sum of its indices
    }
   
    public static int[][] CreateTwoDimArray()
    {
        int [][] tempArray;
        Scanner oScanner = new Scanner(System.in);
       
        System.out.println("Enter size of 1st dimension of two dimensional array");
        int i_1stDimSize = oScanner.nextInt();
        System.out.println("Enter size of 2nd dimension of two dimensional array");
        int i_2ndDimSize = oScanner.nextInt();
       
        tempArray = new int [i_1stDimSize][i_2ndDimSize];
        return tempArray;
    }
   
    public static void InitWithSumOfIndices(int [][]tempArray)
    {
        for (int i=0; i < tempArray.length; i++)
        {
            for (int j=0; j < tempArray[i].length; j++)
            {
                tempArray[i][j] = i + j;
                System.out.print(tempArray[i][j] + " ");
            }
            System.out.println("");            // to get new line after every outer loop iteration
        }
    }
}