In the world of programming, arrays are fundamental data structures that allow developers to store multiple elements of the same type in a single variable. This introduction will guide you through the basics of arrays in Java, explaining how to create, manipulate, and utilize them effectively.
An array is a collection of data items that are stored at contiguous memory locations. In Java, arrays are objects that can store multiple values of the same data type (e.g., integers, floats, strings). Each element in an array can be accessed using an index, and the indexing starts from 0.
To create an array in Java, you need to define the type of elements it will store, the name of the array, and its size.
Here’s an example of how to declare and initialize arrays:
// Declaration
int[] numbers;
// Initialization
numbers = new int[5]; // Array of integers with 5 elements
Alternatively, you can declare and initialize the array in a single step:
int[] numbers = new int[5]; // Array of integers with 5 elements
You can initialize an array with specific values directly:
int[] primes = {2, 3, 5, 7, 11}; // Array of integers initialized with prime numbers
Each element in an array can be accessed using its index. Here’s how you can access and modify elements:
// Accessing elements
System.out.println(numbers[0]); // Access the first element
// Modifying elements
numbers[0] = 10; // Update the first element
Remember, array indexing starts from 0 and goes up to length - 1
.
A single-dimensional array is the simplest form, where elements are stored in a single row.
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println(fruits[1]); // Output: Banana
Multi-dimensional arrays are arrays of arrays, where each element is itself an array. The most commonly used type is the two-dimensional array.
// 2D array representing a matrix
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing an element
System.out.println(matrix[1][2]); // Output: 6
Jagged arrays are arrays of arrays where each sub-array can have different lengths.
// Jagged array
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6}
};
System.out.println(jaggedArray[1][2]); // Output: 5
Trying to access an index outside the array’s bounds will throw an ArrayIndexOutOfBoundsException
.
try {
System.out.println(primes[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}
It’s a good practice to initialize arrays properly to avoid null pointer exceptions.
String[] names = new String[3];
if (names[0] == null) {
names[0] = "Default Name";
}