Java: Arrays

Arrays are containers for storing data of the same type. This lesson covers how to use arrays in Java.

1. What is an Array

An array is a fixed-size collection of elements of the same type.

(1) 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)

2. Declaration and Initialization

(1) Method 1: Declare First, Initialize Later

TEXT 📖 Display only
// Declare array
int[] arr;

// Initialize (allocate space)
arr = new int[5];  // 5 elements, default value is 0

(2) 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
    }
}
▶ Try it Yourself
⚠️ Note: Array indices start at 0. The maximum index is length - 1. Accessing out of bounds throws ArrayIndexOutOfBoundsException.


3. 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

4. Traversing Arrays

(1) Method 1: Regular for Loop

TEXT 📖 Display only
int[] arr = {10, 20, 30, 40, 50};

for (int i = 0; i < arr.length; i++) {
    System.out.println("arr[" + i + "] = " + arr[i]);
}

(2) 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
    }
}
▶ Try it Yourself

5. Arrays Utility Class

java.util.Arrays provides utility methods for array operations.

(1) 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
    }
}
▶ Try it Yourself

6. Two-Dimensional Arrays

A two-dimensional array can be thought of as "an array of arrays."

(1) Declaration and Initialization

TEXT 📖 Display only
// 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
    }
}
▶ Try it Yourself

▶ 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]
    }
}
▶ Try it Yourself

7. Varargs (Variable Arguments)

Varargs allow methods to accept a variable number of arguments.

(1) 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;
    }
}
▶ Try it Yourself
⚠️ Note: Varargs must be the last parameter in a method, and a method can only have one varargs parameter.


8. 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]
    }
}
▶ Try it Yourself

▶ 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
    }
}
▶ Try it Yourself

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).

❓ FAQ

Q Can I resize an array?
A No. Arrays have fixed size. Use ArrayList for dynamic sizing.
Q What happens if I access an invalid index?
A An ArrayIndexOutOfBoundsException is thrown at runtime.
Q How to sort an array?
A Use Arrays.sort() for primitives or Arrays.sort() with a Comparator for objects.

📖 Summary

📝 Exercises

  1. Array operations: Create an array with 10 elements, assign values 1-10, then print in reverse order
  2. Find max/min: Find the maximum and minimum values in an array
  3. Bubble sort: Implement the bubble sort algorithm to sort an array in ascending order

10. Next Lesson

In the next lesson, we'll learn about Practice: Fundamentals — applying the knowledge from the first 7 lessons.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏