Arrays
Arrays are containers for storing data of the same type. This lesson covers how to use arrays in Java.
What is an Array
An array is a fixed-size collection of elements of the same type.
Array Characteristics
| Characteristic | Description |
|---|---|
| Fixed size | Size cannot be changed after creation |
| Same type | All elements must be of the same type |
| Contiguous storage | Elements are stored sequentially in memory |
| Index access | Access elements by index (starting from 0) |
Declaration and Initialization
Method 1: Declare First, Initialize Later
JAVA
// Declare array
int[] arr;
// Initialize (allocate space)
arr = new int[5]; // 5 elements, default value is 0
Method 2: Declare and Initialize
JAVA
// Specify size
int[] arr = new int[5];
// Direct assignment
int[] arr = {1, 2, 3, 4, 5};
Example: Array Initialization
JAVA
public class ArrayInit {
public static void main(String[] args) {
// Method 1: Specify size
int[] arr1 = new int[3];
arr1[0] = 10;
arr1[1] = 20;
arr1[2] = 30;
// Method 2: Direct assignment
int[] arr2 = {10, 20, 30};
// Method 3: new + assignment
int[] arr3 = new int[]{10, 20, 30};
System.out.println(arr2[0]); // 10
System.out.println(arr2[1]); // 20
System.out.println(arr2[2]); // 30
}
}
⚠️ Note: Array indices start at 0. The maximum index is length - 1. Accessing out of bounds throws
ArrayIndexOutOfBoundsException.
Access and Modify
JAVA
int[] arr = {10, 20, 30, 40, 50};
// Access elements
int first = arr[0]; // 10
int third = arr[2]; // 30
// Modify elements
arr[1] = 200; // Change 20 to 200
// Get array length
int len = arr.length; // 5
Traversing Arrays
Method 1: Regular for Loop
JAVA
int[] arr = {10, 20, 30, 40, 50};
for (int i = 0; i < arr.length; i++) {
System.out.println("arr[" + i + "] = " + arr[i]);
}
Method 2: for-each Loop
JAVA
int[] arr = {10, 20, 30, 40, 50};
for (int num : arr) {
System.out.println(num);
}
Example: Calculate Average
JAVA
public class ArrayAverage {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 96, 88};
int sum = 0;
for (int score : scores) {
sum += score;
}
double avg = (double) sum / scores.length;
System.out.println("Average: " + avg); // 87.8
}
}
Arrays Utility Class
java.util.Arrays provides utility methods for array operations.
Common Methods
| Method | Description | Example |
|---|---|---|
sort() |
Sort | Arrays.sort(arr) |
copyOf() |
Copy | Arrays.copyOf(arr, newLen) |
fill() |
Fill | Arrays.fill(arr, value) |
equals() |
Compare | Arrays.equals(arr1, arr2) |
toString() |
Convert to string | Arrays.toString(arr) |
binarySearch() |
Binary search | Arrays.binarySearch(arr, key) |
Example: Using Arrays
JAVA
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
// Sort
Arrays.sort(arr);
System.out.println("Sorted: " + Arrays.toString(arr));
// [1, 2, 3, 5, 8, 9]
// Copy
int[] arr2 = Arrays.copyOf(arr, 3);
System.out.println("First 3: " + Arrays.toString(arr2));
// [1, 2, 3]
// Fill
int[] arr3 = new int[5];
Arrays.fill(arr3, 100);
System.out.println("Filled: " + Arrays.toString(arr3));
// [100, 100, 100, 100, 100]
// Search (must be sorted first)
int index = Arrays.binarySearch(arr, 5);
System.out.println("Index of 5: " + index); // 3
}
}
Two-Dimensional Arrays
A two-dimensional array can be thought of as "an array of arrays."
Declaration and Initialization
JAVA
// Method 1: Specify size
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
// Method 2: Direct assignment
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Example: Traversing a 2D Array
JAVA
public class TwoDArrayDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Traverse
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9
}
}
Example: Matrix Transpose
JAVA
public class MatrixTranspose {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
// Transpose: 2 rows 3 columns → 3 rows 2 columns
int[][] transposed = new int[3][2];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transposed[j][i] = matrix[i][j];
}
}
// Print transposed matrix
for (int[] row : transposed) {
System.out.println(java.util.Arrays.toString(row));
}
// [1, 4]
// [2, 5]
// [3, 6]
}
}
Varargs (Variable Arguments)
Varargs allow methods to accept a variable number of arguments.
Syntax
JAVA
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
Example: Varargs
JAVA
public class VarargsDemo {
public static void main(String[] args) {
System.out.println(sum(1, 2)); // 3
System.out.println(sum(1, 2, 3)); // 6
System.out.println(sum(1, 2, 3, 4, 5)); // 15
}
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
}
⚠️ Note: Varargs must be the last parameter in a method, and a method can only have one varargs parameter.
Common Array Algorithms
Example: Bubble Sort
JAVA
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(java.util.Arrays.toString(arr));
// [1, 2, 3, 5, 8, 9]
}
}
Example: Find Maximum
JAVA
public class FindMax {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum: " + max); // 9
}
}
❓ Frequently Asked Questions
Q Can array size be changed?
A No. Array size is fixed. Use ArrayList if you need dynamic sizing.
Q Do arrays have default values?
A Yes. int defaults to 0, double to 0.0, boolean to false, and reference types to null.
Q What sorting algorithm does Arrays.sort() use?
A For primitives, it uses dual-pivot quicksort. For objects, it uses TimSort (a variant of merge sort).
📖 Summary
- Arrays are fixed-size collections of the same type, with indices starting from 0
- Use regular for or for-each loops for traversal
- The Arrays utility class provides sort, copy, fill, and other methods
- Two-dimensional arrays can be thought of as arrays of arrays
- Varargs allow methods to accept a variable number of arguments
📝 Exercises
- Array operations: Create an array with 10 elements, assign values 1-10, then print in reverse order
- Find max/min: Find the maximum and minimum values in an array
- Bubble sort: Implement the bubble sort algorithm to sort an array in ascending order
Next Lesson
In the next lesson, we'll learn about Practice: Fundamentals — applying the knowledge from the first 7 lessons.



