Java Arrays
Java - Arrays
Section titled “Java - Arrays”Arrays in Java provide a way to store a fixed-size, sequential collection of elements of the same data type. Think of an array as a numbered list of variables, all of the same type.
Instead of declaring individual variables like score1, score2, score3, you can declare a single array variable scores and access elements using an index: scores[0], scores[1], scores[2].
This tutorial covers declaring, creating, initializing, and processing arrays in Java.
Declaring Array Variables
Section titled “Declaring Array Variables”To use an array, you first declare a variable to hold a reference to it. You must specify the data type of the elements the array will hold.
// Preferred modern syntax:dataType[] arrayRefVar;
// Works, but less preferred (C/C++ style):dataType arrayRefVar[];Note: The dataType[] arrayRefVar; style is strongly recommended in modern Java code for better readability.
Example Declarations:
Section titled “Example Declarations:”double[] temperatures; // Declares an array variable to hold doublesString[] names; // Declares an array variable to hold Stringsint[] counts;Creating and Initializing Arrays
Section titled “Creating and Initializing Arrays”Declaration only creates the reference variable; it doesn’t create the actual array object in memory. You create the array using the new operator, specifying the size (number of elements).
// 1. Declare the variabledouble[] myList;// 2. Create the array object and assign its referencemyList = new double[10]; // Creates an array to hold 10 doublesThese steps are usually combined:
dataType[] arrayRefVar = new dataType[arraySize];
// Example:int[] scores = new int[5]; // Creates an array for 5 integersWhen created with new, elements are automatically initialized to default values (0 for numeric types, false for boolean, null for object types).
You can also create and initialize an array in one step using an array initializer (curly braces {}):
dataType[] arrayRefVar = { value0, value1, ..., valueK };
// Examples:double[] rates = { 1.9, 2.9, 3.4, 3.5 }; // Size inferred from valuesString[] weekdays = { "Mon", "Tue", "Wed", "Thu", "Fri" };Accessing Array Elements
Section titled “Accessing Array Elements”Array elements are accessed using a zero-based index (the first element is at index 0). The valid index range is from 0 to arrayRefVar.length - 1.
int[] numbers = { 10, 20, 30, 40 };
// Accessing elements:int firstNumber = numbers[0]; // firstNumber gets 10int thirdNumber = numbers[2]; // thirdNumber gets 30
// Modifying elements:numbers[1] = 25; // Changes the second element to 25
// Getting the array length (number of elements):int size = numbers.length; // size gets 4Attempting to access an element with an index outside the valid range (e.g., numbers[4] or numbers[-1]) will result in an ArrayIndexOutOfBoundsException at runtime.
Processing Arrays
Section titled “Processing Arrays”Loops are commonly used to process array elements.
Using a traditional for loop:
Section titled “Using a traditional for loop:”This loop gives you access to the index, which is useful if you need to modify elements or know the element’s position.
public class ArrayProcessing { public static void main(String[] args) { double[] myList = { 1.9, 2.9, 3.4, 3.5 };
// Print all elements System.out.println("Elements:"); for (int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " "); } System.out.println(); // New line
// Calculate the sum double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is: " + total);
// Find the largest element double max = myList[0]; // Assume first is max initially for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; } } System.out.println("Max is: " + max); }}Expected Output:
Elements:1.9 2.9 3.4 3.5Total is: 11.7Max is: 3.5Using the Enhanced for Loop (foreach):
Section titled “Using the Enhanced for Loop (foreach):”Introduced in Java 5, the enhanced for loop provides a simpler syntax for iterating through all elements when you don’t need the index. It’s generally more readable for traversal.
public class EnhancedForLoop { public static void main(String[] args) { double[] myList = { 1.9, 2.9, 3.4, 3.5 };
// Print all elements using enhanced for loop System.out.println("Elements using enhanced for loop:"); for (double element : myList) { // Read as: "for each double element in myList" System.out.println(element); }
// Calculate sum using enhanced for loop double sum = 0; for (double value : myList) { sum += value; } System.out.println("Sum calculated with enhanced loop: " + sum); }}Expected Output:
Elements using enhanced for loop:1.92.93.43.5Sum calculated with enhanced loop: 11.7Passing Arrays to Methods
Section titled “Passing Arrays to Methods”You can pass arrays to methods just like other object types. Remember that arrays are passed by reference, meaning the method receives a copy of the reference to the original array. Changes made to the array elements within the method will affect the original array.
public class ArrayMethods {
// Method to print array elements public static void printArray(int[] array) { System.out.print("Array elements: [ "); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + (i < array.length - 1 ? ", " : "")); } System.out.println(" ]"); }
// Method to modify an array element public static void modifyElement(int[] arr, int index, int newValue) { if (index >= 0 && index < arr.length) { arr[index] = newValue; // Modifies the original array } }
public static void main(String[] args) { int[] myNumbers = { 3, 1, 2, 6, 4, 2 };
printArray(myNumbers); // Pass the array to the method // Output: Array elements: [ 3, 1, 2, 6, 4, 2 ]
modifyElement(myNumbers, 1, 99); // Modify the element at index 1 printArray(myNumbers); // See the change in the original array // Output: Array elements: [ 3, 99, 2, 6, 4, 2 ]
// You can also pass an anonymous array directly: printArray(new int[] { 10, 20, 30 }); // Output: Array elements: [ 10, 20, 30 ] }}Returning an Array from a Method
Section titled “Returning an Array from a Method”Methods can also return arrays.
public class ReturnArray {
// Method that creates and returns a reversed copy of an array public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; // Return the newly created reversed array }
public static void main(String[] args) { int[] original = { 1, 2, 3, 4, 5 }; int[] reversedArray = reverse(original);
System.out.print("Original: "); ArrayMethods.printArray(original); // Using printArray from previous example // Output: Original: Array elements: [ 1, 2, 3, 4, 5 ]
System.out.print("Reversed: "); ArrayMethods.printArray(reversedArray); // Output: Reversed: Array elements: [ 5, 4, 3, 2, 1 ] }}The Arrays Utility Class
Section titled “The Arrays Utility Class”The java.util.Arrays class provides useful static methods for common array operations, such as sorting, searching, filling, and comparing.
| SN | Method Signature (Simplified) | Description |
|---|---|---|
| 1 | static void sort(primitive[] a) / sort(Object[] a) | Sorts the specified array into ascending order (numerically or lexicographically). Modifies the array in-place. |
| 2 | static int binarySearch(primitive[] a, primitive key) / binarySearch(Object[] a, Object key) | Searches for the specified key within a sorted array using the binary search algorithm. Returns the index of the key if found; otherwise, returns (-(insertion point) - 1). |
| 3 | static boolean equals(primitive[] a, primitive[] a2) / equals(Object[] a, Object[] a2) | Returns true if the two arrays contain the same elements in the same order. For object arrays, compares elements using their equals() method. |
| 4 | static void fill(primitive[] a, primitive val) / fill(Object[] a, Object val) | Assigns the specified value to each element of the specified array. |
| 5 | static primitive[] copyOf(primitive[] original, int newLength) / T[] copyOf(T[] original, int newLength) | Copies the specified array, truncating or padding with default values (0, false, null) if necessary, to obtain the specified length. |
| 6 | static String toString(primitive[] a) / toString(Object[] a) | Returns a string representation of the contents of the specified array (e.g., “[1, 2, 3]”). Useful for printing array contents. |
Example using Arrays utility methods:
import java.util.Arrays;
public class ArraysUtilityDemo { public static void main(String[] args) { int[] numbers = { 5, 2, 8, 1, 9 };
System.out.println("Original array: " + Arrays.toString(numbers)); // Output: Original array: [5, 2, 8, 1, 9]
Arrays.sort(numbers); System.out.println("Sorted array: " + Arrays.toString(numbers)); // Output: Sorted array: [1, 2, 5, 8, 9]
int index = Arrays.binarySearch(numbers, 8); System.out.println("Index of 8: " + index); // Output: Index of 8: 3
int[] filledArray = new int[5]; Arrays.fill(filledArray, 100); System.out.println("Filled array: " + Arrays.toString(filledArray)); // Output: Filled array: [100, 100, 100, 100, 100]
int[] numbersCopy = Arrays.copyOf(numbers, numbers.length); System.out.println("Are numbers and numbersCopy equal? " + Arrays.equals(numbers, numbersCopy)); // Output: Are numbers and numbersCopy equal? true }}Arrays vs. ArrayList
Section titled “Arrays vs. ArrayList”While arrays are fundamental, they have a fixed size. If you need a collection that can grow or shrink dynamically, the java.util.ArrayList class (part of the Java Collections Framework) is often a more flexible choice. ArrayList provides methods to add, remove, and manage elements easily.
Consider using ArrayList when the number of elements isn’t known in advance or changes frequently.