Arrays
Arrays in Java
Objectives
- Understand the nature and purpose of an array.
- Learn how to use arrays in Java programs.
- Work with methods that have array parameters.
- Create methods that return an array.
- Understand the basics of multidimensional arrays.
- Work with multidimensional array parameters and returned values.
- Understand Java's representation of multidimensional arrays.
What is an Array?
- An array is a data structure that holds multiple values of the same type under a single variable name.
- Arrays can store various data types, including primitives (e.g., int, double, boolean) and objects (e.g., String).
- Example:
- An array of integers: 15, 94, 70
- An array of strings: "Apple", "Orange", "Banana"
- Each element in an array is associated with an index, starting from 0.
- In the example above, "Apple" has an index of 0, "Orange" has an index of 1, and "Banana" has an index of 2.
Why Use Arrays?
- Arrays provide a convenient way to manage and process collections of data.
- Consider a scenario with multiple items, like items in a shopping basket:
- Without arrays, you would need to create individual variables for each item:
java String item1 = new String ("eraser"); String item2 = new String ("sharpener"); String item3 = new String ("pencil"); - This approach becomes cumbersome when dealing with a large number of items (e.g., 100 items in a basket).
- Without arrays, you would need to create individual variables for each item:
- Arrays simplify tasks such as calculating the total bill for items in a basket.
- Instead of referencing each item individually, you can use a single array variable and iterate through its elements.
Creating an Array
- To create an array in Java, you need to specify the base type (the type of elements the array will hold) and the size (the number of elements).
- Syntax:
java String[] items = new String[3];String[]: Declares an array nameditemsthat can hold strings.new String[3]: Reserves space in memory for 3 string elements, with indices 0, 1, and 2.
Accessing Array Elements
- Individual elements in an array can be accessed using their index within square brackets.
- Example:
java items[0] = "eraser"; items[1] = "sharpener"; items[2] = "pencil";items[0]refers to the first element (at index 0), which is assigned the value "eraser".
Calculating Total Bill with Arrays
- Arrays facilitate iterating through a list of products to calculate the total bill.
- You can write a loop that accesses each product in the array and adds its price to a running total.
- Example:
- The illustrations in the transcript (pages 13 - 20) demonstrate how a loop can iterate through an array of items and calculate a result. The loop variable
iincrements from 0 to the array length, accessing each element in turn.
- The illustrations in the transcript (pages 13 - 20) demonstrate how a loop can iterate through an array of items and calculate a result. The loop variable
Array Properties
- Arrays have a
lengthproperty that indicates the number of elements in the array. lengthis a constant, not a method.- For the
itemsarray created earlier,items.lengthwould be equal to 3. - The first element of an array is at index 0.
- The last element of an array is at index
items.length - 1.
One-Dimensional Arrays
- An array with a single row of elements is called a one-dimensional array.
- It is a special variable that stores a sequence of data items of the same type, accessible by their index.
- The number of elements in an array is its length.
Syntax
- To create a one-dimensional array, use the following syntax:
java BaseType[] arrayName = new BaseType[length];BaseType: The data type of the elements in the array (e.g.,int,double,String).arrayName: A valid Java identifier for the array.new: Java operator used to allocate memory for the array.length: The number of elements in the array; must be an integer expression.
Creating a One-Dimensional Array (Example)
- Example:
java int[] counts = new int[4]; double[] values = new double[size];- The first statement creates an array named
countsthat can hold four integers. - The second statement creates an array named
valuesthat can hold doubles; the size depends on the value of the variablesizeat runtime.
- The first statement creates an array named
Another Way to Create a One-Dimensional Array
- Arrays can also be created in a two-step process:
java baseType[] arrayName; arrayName = new baseType[length];- You cannot use the array until you specify its size in the second step.
One-Dimensional Array Size
- The value inside the square brackets when creating an array must be a positive integer.
- It is recommended to use named constants instead of integer literals for the array size.
java final int NUMBER_OF_READINGS = 100; double[] pressure = new double[NUMBER_OF_READINGS]; - The size of the array can be read from the keyboard at runtime, but it must be non-negative. A negative size will result in a
NegativeArraySizeException. - Arrays with zero elements are allowed and can have special uses.
Initializing One-Dimensional Arrays
- Arrays can be initialized at the time of declaration using a comma-separated sequence of elements enclosed in curly braces:
java int[] a = {1, 2, 3, 4};- This creates an array with four elements:
a[0]is 1,a[1]is 2,a[2]is 3, anda[3]is 4.
- This creates an array with four elements:
Initializing One-Dimensional Arrays Using Assignment Statements
Arrays can also be initialized using assignment statements, either one at a time or within a loop:
count[0] = 10; count[1] = 15; for (int i = 0; i < count.length; i++) { count[i] = i * 5; }
Partially Filled One-Dimensional Arrays
- The capacity of an array is the number of elements allocated when the array is created (
a.length). - You may not always use all the elements in an array, resulting in a partially filled array.
- In such cases, you need to keep track of how many elements are actually used.
The Instance Variable length
- Arrays have a public instance variable named
lengththat stores the length of the array. - The value of
lengthcannot be changed; it isfinal.java int[] count = new int[4]; // count.length has a value of 4 // count.length = 10; // Illegal!
Accessing Elements of 1-D Arrays
- Array elements are accessed using their index, which starts at 0.
- You can use any expression of type
intas an index. - Syntax:
java arrayName[index]
Rewriting Code with a For Statement
The following code snippets are equivalent:
int[] count = {7, 14, 1, -60}; // Using a while loop: int i = 0; while (i < count.length) { System.out.println(count[i]); i++; } // Using a for loop: for (int i = 0; i < count.length; i++) { System.out.println(count[i]); }
Creating and Accessing Arrays - Example: Calculating Average Temperature
- To read 7 temperatures from the user and show which are above and below the average temperature.
Notes on One-Dimensional Array Indices
- The index of the first element is 0.
- The last index is
arrayName.length - 1. - Array indices must be within bounds to be valid.
- Accessing elements outside the bounds results in a runtime error, specifically an
ArrayIndexOutOfBoundsException.
Multidimensional Arrays (Two-Dimensional Arrays)
- Arrays with more than one dimension are called multidimensional arrays.
- A two-dimensional array can be thought of as a table with rows and columns.
Two-Dimensional Arrays Basics
To represent a table in Java, you can use a two-dimensional array.
Elements in a two-dimensional array are accessed using two indices: a row index and a column index.
table[3][2] = 1262;table[3][2]refers to the element at row 3, column 2.
Two-dimensional arrays are arrays of arrays.
Declaring and Creating a Two-Dimensional Array
- Syntax:
java BaseType[][] arrayName = new BaseType[ROWS][COLUMNS];
ORjava BaseType[][] arrayName; arrayName = new BaseType[ROWS][COLUMNS];
Ragged Arrays
- In a ragged array, the rows can have different lengths.
Initializing Two-Dimensional Arrays
- Two-dimensional arrays can be initialized at declaration time using nested curly braces:
java int[][] b = {{ 1, 2 }, { 3, 4 }};
Accessing Elements in Two-Dimensional Arrays
- Elements are accessed using the array name and two indices.
- Nested for loops are commonly used to iterate through the elements of a two-dimensional array.
Copying Arrays
- Array variables contain references (memory addresses) to arrays.
- Assignment copies the reference, not the array itself.
- Arrays are objects like
String. - The assignment operator
=copies the memory address. - The equality operator
==tests whether two arrays are stored in the same memory location.
Copying and Traversing One-Dimensional Arrays
- To create an actual copy of an array, you need to create a new array and copy the elements from the original array to the new array.
- Looping through the elements of an array is called a traversal.
Copying and Traversing Two-Dimensional Arrays
- To copy a two-dimensional array, create a new array and copy the elements from the original array.
Arrays in Methods
- Arrays can be passed to methods as arguments.
Arrays and Methods
- A single element or indexed variable can be passed as a method argument (pass by-value).
- The entire array can be passed as a method argument (pass by-reference).
- Changes made to the array inside the method will affect the original array.
Indexed Variables as Method Arguments
Example:
public static void myMethod(int n) { n = 0; } int[] arr = {1, 2, 3}; myMethod(arr[0]); // Pass by value, arr[0] remains 1
Entire Arrays as Arguments to a Method
- Syntax:
java public <static> return_Type method_Name(Base_Type[] arrayName) public <static> return_Type method_Name(Base_Type[][] arrayName) - The array parameter in a method heading does not specify the length.
- An array of any length can be passed to the method.
- Inside the method, elements of the array can be changed.
Returning Arrays from Methods
- A method can return an array.
- When a method returns an array, the reference of the array is returned (memory address!).
- Syntax:
java public static BaseType[] methodName(parameters) { // Code to create and populate the array return arrayName; }
More Examples on One-Dimensional Arrays
- Copying One-Dimensional Arrays - Example: Comparing two arrays
Traversing One-Dimensional Arrays
- Traversing an array to "search" for a particular element.
- Accumulating values in an array (e.g., summing the elements).
Summary
- An array is a collection of variables all of the same type.
- Arrays are objects, created with the operator
new. - Each item in an array is called an element.
- Elements are numbered starting with 0, ending with 1 less than length.
- In an array, each element's location number is called the index; indices start with 0 rather than 1.
- The size of an array must be specified by an
intorshortvalue and notlong. - The size of the array cannot be altered (once initialized). However, an array reference can be made to point to another array.
- Indexed variables can be used as parameters – treated like variables of the base type.
- The entire array can be passed as a parameter to a method.
- A method return value can be an array.
- A partially filled array usually stores values in the initial segment; use an
intto track how many are used. - Multidimensional arrays are implemented as an array of arrays.
- Treat two-dimensional arrays as a table with rows and columns.