Java Programming: Arrays

Java Programming–Arrays

General Format

<strong style="color:#9013fe"><span style="color:#9013fe">data type </span><span style="color:#417505"><span style="color:#417505">[] </span><span style="color:#4a90e2">arrayName <span style="color:#f5a623"><span style="color:#000000">=</span>&nbsp;<span style="color:#d0021b">new <span style="color:#9013fe"><span style="color:#9013fe">data type </span><span style="color:#f5a623">[length]</span></span></span></span></span></span></strong>
  • data type–the array can only hold elements of the same data type (char, boolean, int, double, String, etc.)
  • [] → indicates array
  • array name–must be lowercase first then camel cased
    • programmer determines array name
    • the array should have the word Array in its name
  • new keyword indicates that it’s an Object
  • length–the array’s length tells us how many elements it will hold
    • the index values of the array will always start from 0 and end at the length – 1
<u>example 1:</u>&nbsp; &nbsp; &nbsp;int [] numberArray = new int[5];

numberArray stores 5 integer values in the array

52379
index 0            index 1             index 2             index 3             index 4

Storing Data in an Array

  • assign a value to the index
    • numberArray[0] = 5;
    • numberArray[1] = 2;
    • numberArray[4] = 9;
  • initialize the array
    • int [] numberArray = {5, 2, 3, 7, 9};
  • use a for loop to store data (best for larger array sizes!)
int [] numberArray = new int[5];

for (int index = 0; index 
System.out.println("Enter a value to store in index " + index + ":");
numberArray[index] = input.nextInt();
}

Using the

.length

  • .length is used to determine the length of the array
  • this is especially to use when iterating over the array for input and output because if you decide to change the length of the array, you wouldn’t have to worry about the out of bounds indexing
    • numberArray.length should give 5 as the value since the numberArray has length 5

Printing Out What is Stored In an Array

  • use a for loop to output data (best for larger array sizes!)
for (int index = 0; index 
System.out.print(numberArray[index] + " ");
}

Java Programming–Arrays (…cont.)

Enhanced For Loop

  • We can print out the contents of our arrays using an enhanced for loop–a simplified version of the for loop
  • General format: for (data type value : arrayName) {}
    • data type → the data type that the array holds
    • value → word used to describe what is stored in the array (i.e. student, number, amount, hour, etc.)
    • : → means “from”
      • so we read the example below as, “for the integer number from the numberArray”
    • arrayName → whatever the programmer named the array
for (int number : numberArray) {
System.out.print(number + " ");
}

Out Of Bounds Exception

  • it is important to know that the array’s index values ALWAYS START AT 0 and END AT LENGTH – 1

recall our array int [] numberArray = {5, 2, 3, 7, 9};  

  • numberArray[-1] → give an out of bounds exception because there is no index -1
  • numberArray[5] → give an out of bounds exception because there is no index 5
  • numberArray[7] → give an out of bounds exception because there is no index 7

This exception can happen while iterating over an array and having the index variable access an index that doesn’t exist from the array

for (int index = 0; index <span style="background-color:#f8e71c"> numberArray.length; index++) {
System.out.print(numberArray[index] + " ");
}
  • in this particular example, the index starts at 0 and ends now at 5, which we already discussed, doesn’t exist
    • it had to start at 0 and end at 4 so the

Built-in Methods from java.util.Arrays

  • Built-in methods
    • Arrays.sort(numberArray); → {2, 3, 5, 7, 9}
      • sorts the contents of the array to be in increasing order
    • Arrays.binarySearch(numberArray, 2); → should give 5 after the array has been sorted
      • checks to see if a value exists in the array and returns the index that that value is in if it does exist
    • Arrays.fill(numberArray, 7); → {7, 7, 7, ,7 ,7}
      • fills the whole array with whatever value you want
    • Arrays.equals(numberArray, numberArray2); → sees if two arrays are equal
      • sees if two arrays are equal
      • int [] numberArray = {5, 2, 3, 7, 9};
      • int [] numberArray2 = {5, 2, 3, 7, 9};
      • Arrays.equals(numberArray, numberArray2); → equal
      • int [] numberArray3 = {5, 2, 3, 7, 9};
      • int [] numberArray4 = {5, 3, 2, 7, 9};
      • Arrays.equals(numberArray3, numberArray4); → not equal because the values at index 1 and index 2 are not the same!

Java Programming–Arrays (…cont.)

Variable-Length Argument Lists

  • In Java, an argument of a method can accept arbitrary number of values. 
  • This argument that can accept variable number of values is called varargs
    • used to create methods that receive an unspecified number of arguments
  • Parameter type followed by an ellipses (…) indicates that the method receives a variable number of arguments of that particular type
  • We can pass an array or a variable number of arguments to a variable-length parameter
  • When invoking a method with a variable number of arguments, Java creates an array and passes the arguments to it

mWiK1wAUy9bMwMijYF3UOSQGKaIsMz1xk3kfAYQp96LgthDwl27E11YzGnGCX32W2GZoZ2yHxUDD7b8SyWQr9Q48mQNQppfZF2EOGFPYaPYJjH-WYyxrTOR4Ek2j63d5f0gXZokG6fiKGNN-lejf4E7CqA=s2048

  • We can add any number of arguments of the same data type to a method because Java handles the given arguments as elements in an array

Two-Dimensional Arrays AXWmgm9etMpzAAAAAElFTkSuQmCC  

  • also known as an array of arrays
  • thought of as having rows and columns

General Format 

data type [][] arrayName = new data type [row length][column length]

  • you would declare and initialize or declare and create an array the same way you would for a one-dimensional array

example 2:     int [][] twoDimArray = new int[4][2];

  • twoDimArray stores 8 integer values in the array
  • twoDimArray has 4 rows and 2 columns
    • so the row indexes start at 0 and end at 3 (length – 1 = 4 – 1 = 3)
    • and the column indexes start at 0 and end at 1 (length – 1 = 2 – 1 = 1)
  • to initialize the array, I would have written it as:
    • int [][] twoDimArray = {{5, 7}, {6, 2}, {14, 8}, {4, 9}}; 


Java Programming–Arrays (…cont.)

Two-Dimensional Arrays AXWmgm9etMpzAAAAAElFTkSuQmCC …(cont.)

  • recall our two-dimensional array int [][] twoDimArray = new int[4][2];
  • to manually store data in the array (especially for large array sizes), I can use a nested for loop to store the integer values in each row and column indexes

//this stores values in the row indexes

for (int row = 0; row

//this stores values in the column indexes

for (int column = 0; column

System.out.print(“Enter the value: “);

twoDimArray[row][column] = input.nextInt();

}

System.out.println()

}

  • to print out the contents stored in the array, I would use a nested for loop

for (int row = 0; row

for (int column = 0; column

System.out.print(twoDimArray[row][column] + ” “);

}

System.out.println()

}

  • .length is used to determine the length of the array, just like with one-dimensional arrays
    • twoDimArray.length → row length and should give 4 as the output since the array has a row length of 4
    • twoDimArray[row].length → column length and should give 2 as the output since the array has a column length of 2
  • two-dimensional arrays can be used to store data in a frequency table, to represent a matrix, to store coordinate points, etc.