Arrays
What is an Array?
An array is a fixed-size container that stores multiple values of the same type under one variable name. Instead of creating score1, score2, score3, you can store them all in a single array.
Declaring and Creating Arrays
// Declare and initialize with values directly
int[] scores = {85, 90, 78, 92, 88};
// Declare, then create with a fixed size
int[] numbers = new int[5]; // creates an array of 5 zeros
numbers[0] = 10;
numbers[1] = 20;
Note: Array indexing starts at0, not1. So in an array of 5 elements, valid indexes are0through4.
Accessing and Updating Elements
int[] scores = {85, 90, 78, 92, 88};
System.out.println(scores[0]); // 85, the first element
System.out.println(scores[4]); // 88, the last element
scores[2] = 100; // update the third element
System.out.println(scores[2]); // 100Finding the Length
Every array has a built-in length property (note: no parentheses, unlike a method call).
int[] scores = {85, 90, 78, 92, 88};
System.out.println(scores.length); // 5Looping Through an Array
int[] scores = {85, 90, 78, 92, 88};
// Using a standard for loop
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + ": " + scores[i]);
}
// Using a for-each loop
for (int score : scores) {
System.out.println(score);
}Multidimensional Arrays
Java supports arrays of arrays, most commonly used to represent grids or matrices.
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(grid[1][2]); // 6 (row index 1, column index 2)
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}Arrays of Other Types
String[] names = {"Alice", "Bob", "Charlie"};
double[] prices = {19.99, 5.49, 100.0};
boolean[] flags = {true, false, true};Common Array Utility Methods
The java.util.Arrays class provides handy helper methods:
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers); // sorts in place: [1, 2, 5, 8, 9]
System.out.println(Arrays.toString(numbers)); // prints [1, 2, 5, 8, 9]| Method | Purpose |
|---|---|
Arrays.sort(arr) | Sorts the array in ascending order |
Arrays.toString(arr) | Converts array to a readable string |
Arrays.equals(a, b) | Checks if two arrays have identical contents |
Arrays.fill(arr, val) | Fills every slot in the array with the same value |
Important: Arrays in Java have a fixed size once created — you cannot add or remove elements. If you need a resizable collection, use anArrayListfrom the Java Collections Framework instead.
Coming up next: Methods — how to organize your code into reusable, named blocks.