Arrays
Dashboard
Topic 7/30
Home › Arrays

📦 Arrays

Discover how to store and manipulate multiple values of the same type using arrays in Java.

Array Basics

An array is a fixed-size container that holds elements of the same type. Indexes are 0-based.

ArrayBasics.java Java
public class ArrayBasics {
    public static void main(String[] args) {
        // Declaration and Initialization
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Enhanced for loop (for-each)
        for (int n : numbers) {
            System.out.println(n);
        }
        
        System.out.println("Length: " + numbers.length);
    }
}

Common Array Operations

The java.util.Arrays class provides handy utility methods for sorting, searching, and more.

ArraySorting.java Java
import java.util.Arrays;

public class ArraySorting {
    public static void main(String[] args) {
        int[] arr = {5, 2, 9, 1, 6};
        
        Arrays.sort(arr);
        System.out.println("Sorted: " + Arrays.toString(arr));
        
        int index = Arrays.binarySearch(arr, 9);
        System.out.println("Index of 9: " + index);
    }
}
FindLargestSmallest.java Java
public class FindLargestSmallest {
    public static void main(String[] args) {
        int[] nums = {43, 78, 21, 9, 85, 12};
        int min = nums[0];
        int max = nums[0];
        
        for (int num : nums) {
            if (num < min) min = num;
            if (num > max) max = num;
        }
        
        System.out.println("Min: " + min + ", Max: " + max);
    }
}

Multidimensional Arrays

You can create 2D arrays (matrices) to represent grids, tables, and complex data structures.

MatrixMultiplication.java Java
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] a = { {1, 2}, {3, 4} };
        int[][] b = { {2, 0}, {1, 2} };
        int[][] c = new int[2][2];
        
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 2; k++) {
                    c[i][j] += a[i][k] * b[k][j];
                }
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}