Fundamental Programming Structures in Java: Arrays

What we’ll cover

Arrays

int[] array;
int[] array = new int[100];
int[] array = new int[100];
int numberOfElements = array.length;

Array Initializers and Anonymous Arrays

int[] smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
int[] smallerPrimes = { 2, 3, 5, 7, 11, 13 };

Array Copying

Arrays can be set from one variable to another. However, then both variables refer to the same array.

int[] smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12; // now smallPrimes[5] is also 12
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);

The “for each” Loop

for (VariableType variableName : iterableType) {
  // body of for loop
  // ...
}
int[] smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
for (int currentPrime : smallPrimes) {
  System.out.println(currentPrime);
} 
int[] smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
int numberOfElements = smallPrimes.length;
for (int currentLoopNumber = 0; currentLoopNumber < numberOfElements; currentLoopNumber++) {
  int currentPrime = smallPrimes[currentLoopNumber];
  System.out.println(currentPrime);
}
int[] smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
int numberOfElements = smallPrimes.length;
int currentLoopNumber = 0;
while(currentLoopNumber < numberOfElements) {
  int currentPrime = smallPrimes[currentLoopNumber];
  System.out.println(currentPrime);
  currentLoopNumber++;
}

Array Sorting

int[] a = new int[10000];
Arrays.sort(a)

Multidimensional Arrays

double[][] balances;

You cannot use the array until you initialize it.

balances = new double[NYEARS][NRATES];
int[][] magicSquare =
{
    {16, 3, 2, 13},
    {5, 10, 11, 8},
    {9, 6, 7, 12},
    {4, 15, 14, 1}
};

balances[i][j]