Java Arrays
An array is a basic data structure that is a container that can hold a fixed number of elements of the same type. The size of an array is determined at creation and cannot be changed afterward.
Declaring Arrays
Declaring an array variable does not create an array in memory; it only tells the compiler that this variable will refer to an array of a specific type.
Syntax:
Example:
Creating and Initializing Arrays
After declaring an array, you need to use the new keyword to create the array and specify its size.
1. Create and Specify Size
After creating an array, its elements are automatically initialized to default values (0 for numbers, false for booleans, null for reference types).
2. Create and Initialize Directly
You can create and initialize an array at the same time by providing an initializer list using curly braces {}. The compiler automatically determines the array size based on the number of elements.
Accessing Array Elements
You can access or modify any element in an array through its index. Array indexing starts at 0, and the maximum index is array length - 1.
Array length Property
Every array has a length property (note: it's not a method) that indicates the number of elements the array can hold.
Iterating Over Arrays
Iterating over arrays is a common operation, usually done using loops.
Using for Loop
Using Enhanced for Loop (For-Each)
This is a more concise and recommended way to iterate, and it's less error-prone.
Multi-dimensional Arrays
Java also supports multi-dimensional arrays, which are essentially "arrays of arrays". The most common is the two-dimensional array, which can be thought of as a table or matrix.
java.util.Arrays Utility Class
Java provides an Arrays utility class that contains many static methods for manipulating arrays.
Arrays.toString(array): Returns a string representation of the array contents, ideal for printing arrays.Arrays.sort(array): Sorts the array in ascending order.Arrays.fill(array, value): Fills all elements of the array with the specified value.Arrays.equals(array1, array2): Compares whether the contents of two arrays are exactly equal.Arrays.binarySearch(array, key): Performs a binary search on a sorted array.