Chapter 7: Arrays and ArrayList
Introduction to Arrays
• Primitive variables are limited to holding a single value, whereas arrays are more flexible structures designed to hold collections of like values, accessible via an index. This capability makes arrays an essential data structure in programming for handling multiple data points efficiently.
• An array can consist of various data types, including integers, characters, and floating-point numbers, but it must maintain consistency in data type throughout its elements. This ensures that operations on the array's contents are homogenous and predictable, contributing to performance optimizations in algorithms.
Creating Arrays
• To create an array, you first require an object reference that will hold the array, such as
int[] numbers;
, allowing the program to allocate memory for the array.• An array must be instantiated with a specified size, denoted by using the
new
keyword followed by the desired type and size in brackets (e.g.,numbers = new int[6];
). This allocation reserves memory for the array.• Combining declaration and instantiation can be done in one concise line:
int[] numbers = new int[6];
, which enhances readability in your code.• Valid types for arrays can include but are not limited to:
float[]
for floating-point numbers,char[]
for characters,long[]
for larger integer values, anddouble[]
for double-precision floating-point numbers. Understanding the types you can use for arrays is crucial in optimizing memory usage based on expected data.• An array's size must always be a non-negative integer, and once defined, it cannot be altered, meaning that arrays have a fixed size, necessitating careful planning during their creation to ensure sufficient capacity for future needs.
Accessing Elements
• Elements within an array can be accessed using the reference name followed by a subscript that denotes the specific index of the desired element (e.g.,
numbers[0] = 20;
). This allows direct manipulation of the stored data.• It's important to note that array indices begin at 0, meaning the first element is accessed with index 0 and the last element is accessed with index
length - 1
, which is critical for correctly iterating through elements without exceeding the bounds of the array.Bounds Checking and Errors
• To ensure robustness in your code and prevent errors, it's essential to always check the bounds of the array before accessing its elements. For example, attempting to access index 100 on an array of size 100 will result in an
ArrayIndexOutOfBoundsException
, which indicates that the requested index is out of the permissible range. Proper error handling can improve program stability and user experience.Array Initialization
• For initializing arrays with a predetermined set of values, an initialization list can be used:
int[] days = {31, 28, 31, 30, 31, ...};
. This approach facilitates quick and clean initialization of the array without needing to assign values individually, streamlining the process when the values are known at compile time.Alternate Array Declaration
• Syntax for declaring arrays can vary slightly between languages and styles, allowing for flexibility: either
int[] numbers;
orint numbers[];
can be used, with both achieving the same result and indicating thatnumbers
is an array of integers.• You can also declare multiple arrays in a single line to minimize redundancy (e.g.,
int[] a = new int[5], b = new int[10];
).Processing Array Contents
• Processing elements within an array is similar to processing primitive variables. For instance, you can compute values directly from array elements—such as
grossPay = hours[3] * payRate;
—enabling straightforward calculations as part of typical computational tasks.• Arrays also support evaluations and conditional statements within loops (e.g.,
for
,while
), allowing for dynamic handling of data based on the content of the array during program execution.Array Length
• The array's size can be obtained using the
length
property (e.g.,int size = temperatures.length;
), which is also useful for dynamically iterating through arrays and performing operations without hardcoding array sizes, enhancing code flexibility and maintainability.Enhanced for Loop
• The enhanced
for
loop facilitates a more concise and readable syntax for processing array elements in a read-only manner:for(datatype elementVariable : array) statement;
, which simplifies iteration without the need for explicit index management, reducing potential coding errors.User-Defined Array Size
• To allow for dynamic array sizing based on user input, you can capture input through mechanisms such as
numTests = keyboard.nextInt(); tests = new int[numTests];
, making your application adaptable to varying requirements. This feature enhances user interaction and the general usability of your program by accommodating varying sizes of datasets as they evolve.
Example 1: Declaring and Initializing an Integer Array
int[] numbers = new int[]{1, 2, 3, 4, 5};
This code snippet initializes an integer array called numbers
with five elements.
Example 2: Accessing Array Elements
System.out.println(numbers[0]); // Outputs: 1
This prints the first element of the numbers
array.
Example 3: Modifying an Array Element
numbers[2] = 10; // Change the third element to 10
This updates the value of the third element in the array from 3 to 10.
Example 4: Looping Through an Array Using Enhanced For Loop
for(int number : numbers) {
System.out.print(number + " ");
}
This code iterates over the numbers
array and prints each number.
Example 5: Array of Strings
String[] fruits = {"Apple", "Banana", "Cherry"};
This declares and initializes a string array called fruits
.
Example 6: Multidimensional Array
int[][] matrix = {{1, 2}, {3, 4}};
This example demonstrates a 2D array (matrix) with two rows and two columns.
Example 7: User-Defined Size Array
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of tests: ");
int numTests = keyboard.nextInt();
int[] tests = new int[numTests];
This code allows user input to define the size of the tests
array, making it dynamic based on user requirement.
Example 8: Summing Array Elements
int sum = 0;
for(int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("Sum: " + sum);
This code iterates through the numbers
array and calculates the sum of its elements.
Example 9: Conditional Access
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] > 2) {
System.out.println("Number greater than 2: " + numbers[i]);
}
}
This code checks if any number in the numbers
array is greater than 2 and prints it if so.