Array Basics
Arrays are a fundamental data structure in Java, allowing you to store and manage collections of elements of the same type efficiently. Here is a simple and comprehensive guide to everything you need to know about arrays in Java.
What is an Array?
-
An array is a container object that holds a fixed number of values of a single type (e.g., int, String, double).
-
The size (length) of an array is set when it is created and cannot be changed.
-
Arrays use a zero-based index system: the first element is at index 0, the second at index 1, and so on.
Declaring and Initializing Arrays
Declaration Syntax:
int[] numbers; // Preferred style
// or
int numbers[]; // Also valid
Initialization:
- You must allocate memory for the array using the
newkeyword or initialize it directly.
numbers = new int[5]; // Creates an array of size 5 with default values (0s)
Declaration + Initialization:
int[] numbers = new int[5]; // Array of 5 integers
String[] names = {"Alice", "Bob", "Charlie"}; // Direct initialization
Default Values:
-
Numeric types (int, double, etc.): 0
-
boolean: false
-
Objects (like String): null
Accessing and Modifying Array Elements
- Access elements using their index:
int x = numbers[0]; // Gets the first element
numbers[1] = 42; // Sets the second element to 42
- Array indices start at 0 and go up to
array.length - 1.
Array Length
- Use the
.lengthproperty to get the size of the array:
int size = numbers.length;
Types of Arrays in Java
1. Single-Dimensional Arrays
- A simple list of elements.
int[] arr = {1, 2, 3, 4, 5};
2. Multi-Dimensional Arrays
- Arrays of arrays (e.g., tables or matrices).
int[][] matrix = new int[3][3]; // 3x3 grid
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
3. Jagged Arrays
- Multi-dimensional arrays where sub-arrays can have different lengths.
int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};
Looping Through Arrays
- Use a
forloop or enhancedforloop to iterate over elements:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for loop
for (int num : numbers) {
System.out.println(num);
}
Array Utility Methods
Java provides the java.util.Arrays class with many helpful methods:
-
Sorting:
Arrays.sort(arr); -
Binary Search:
Arrays.binarySearch(arr, value); -
Filling:
Arrays.fill(arr, value); -
Comparing:
Arrays.equals(arr1, arr2);
Key Points and Limitations
-
Arrays are fixed in size; you cannot add or remove elements after creation.
-
All elements must be of the same data type.
-
Arrays can store primitive types or objects (including arrays of objects).
-
Trying to access an index outside the array bounds causes an
ArrayIndexOutOfBoundsException.
Example: Complete Array Usage
int[] scores = new int[3]; // Declaration and memory allocation
scores[0] = 90; // Assign values
scores[1] = 85;
scores[2] = 78;
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + ": " + scores[i]);
}