Java Array Methods

Built-in methods for working with arrays and collections

📚 What are Array Methods?

Array methods are built-in functions that help you manipulate, search, and organize collections of data in Java. They make working with multiple values simple and efficient.


// Basic array methods example
import java.util.Arrays;

int[] numbers = {3, 1, 4, 1, 5};
Arrays.sort(numbers);                    // Sort array
System.out.println(Arrays.toString(numbers)); // [1, 1, 3, 4, 5]
System.out.println(numbers.length);     // 5
                                    

Types of Array Methods

📏

Basic Properties

Get information about arrays

length toString() equals()
🔍

Search & Find

Find elements in arrays

binarySearch() contains() indexOf()
🔄

Sort & Organize

Arrange array elements

sort() reverse() shuffle()
📋

Copy & Fill

Create and modify arrays

copyOf() fill() clone()

🔹 Basic Array Properties

Get essential information about your arrays:

import java.util.Arrays;

public class ArrayBasics {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        String[] names = {"Alice", "Bob", "Charlie"};
        
        // Get array length
        System.out.println("Numbers length: " + numbers.length);
        System.out.println("Names length: " + names.length);
        
        // Convert array to string for display
        System.out.println("Numbers: " + Arrays.toString(numbers));
        System.out.println("Names: " + Arrays.toString(names));
        
        // Access individual elements
        System.out.println("First number: " + numbers[0]);
        System.out.println("Last name: " + names[names.length - 1]);
    }
}

Output:

Numbers length: 5

Names length: 3

Numbers: [10, 20, 30, 40, 50]

Names: [Alice, Bob, Charlie]

First number: 10

Last name: Charlie

🔹 Sorting and Organizing Arrays

Arrange your array elements in different orders:

import java.util.Arrays;
import java.util.Collections;

public class ArraySorting {
    public static void main(String[] args) {
        Integer[] scores = {85, 92, 78, 96, 88};
        String[] fruits = {"banana", "apple", "cherry", "date"};
        
        // Sort numbers in ascending order
        Arrays.sort(scores);
        System.out.println("Sorted scores: " + Arrays.toString(scores));
        
        // Sort strings alphabetically
        Arrays.sort(fruits);
        System.out.println("Sorted fruits: " + Arrays.toString(fruits));
        
        // Sort in descending order
        Arrays.sort(scores, Collections.reverseOrder());
        System.out.println("Descending scores: " + Arrays.toString(scores));
    }
}

Output:

Sorted scores: [78, 85, 88, 92, 96]

Sorted fruits: [apple, banana, cherry, date]

Descending scores: [96, 92, 88, 85, 78]

🔹 Searching in Arrays

Find specific elements in your arrays:

import java.util.Arrays;

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        String[] colors = {"red", "blue", "green", "yellow"};
        
        // Linear search (manual)
        int target = 30;
        int position = -1;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                position = i;
                break;
            }
        }
        System.out.println(target + " found at position: " + position);
        
        // Binary search (array must be sorted)
        Arrays.sort(numbers);
        int index = Arrays.binarySearch(numbers, 40);
        System.out.println("Binary search for 40: " + index);
        
        // Check if array contains element (using Arrays.asList)
        boolean hasBlue = Arrays.asList(colors).contains("blue");
        System.out.println("Contains 'blue': " + hasBlue);
    }
}

Output:

30 found at position: 2

Binary search for 40: 3

Contains 'blue': true

🔹 Copying and Filling Arrays

Create new arrays and fill them with values:

import java.util.Arrays;

public class ArrayCopyFill {
    public static void main(String[] args) {
        int[] original = {1, 2, 3, 4, 5};
        
        // Copy entire array
        int[] copy1 = Arrays.copyOf(original, original.length);
        System.out.println("Full copy: " + Arrays.toString(copy1));
        
        // Copy part of array
        int[] copy2 = Arrays.copyOfRange(original, 1, 4);
        System.out.println("Partial copy: " + Arrays.toString(copy2));
        
        // Create and fill array
        int[] filled = new int[5];
        Arrays.fill(filled, 99);
        System.out.println("Filled array: " + Arrays.toString(filled));
        
        // Fill part of array
        int[] partial = {1, 2, 3, 4, 5};
        Arrays.fill(partial, 1, 4, 0);
        System.out.println("Partially filled: " + Arrays.toString(partial));
    }
}

Output:

Full copy: [1, 2, 3, 4, 5]

Partial copy: [2, 3, 4]

Filled array: [99, 99, 99, 99, 99]

Partially filled: [1, 0, 0, 0, 5]

🔹 Comparing Arrays

Check if arrays are equal or compare their contents:

import java.util.Arrays;

public class ArrayComparison {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
        int[] array2 = {1, 2, 3, 4, 5};
        int[] array3 = {5, 4, 3, 2, 1};
        
        // Compare arrays for equality
        System.out.println("array1 equals array2: " + Arrays.equals(array1, array2));
        System.out.println("array1 equals array3: " + Arrays.equals(array1, array3));
        
        // Compare arrays lexicographically
        System.out.println("Compare array1 to array3: " + Arrays.compare(array1, array3));
        
        // Hash code for arrays
        System.out.println("Hash code of array1: " + Arrays.hashCode(array1));
        System.out.println("Hash code of array2: " + Arrays.hashCode(array2));
    }
}

Output:

array1 equals array2: true

array1 equals array3: false

Compare array1 to array3: -1

Hash code of array1: 29615266

Hash code of array2: 29615266

🔹 Practical Array Examples

Real-world applications of array methods:

Common Use Cases:

  • Student grades: Sort and find highest/lowest scores
  • Inventory: Search for products, organize by price
  • Data analysis: Find duplicates, calculate statistics
  • Gaming: High score lists, player rankings
import java.util.Arrays;

public class PracticalArrays {
    public static void main(String[] args) {
        // Student grades example
        int[] grades = {85, 92, 78, 96, 88, 92, 85};
        
        // Find highest and lowest grades
        Arrays.sort(grades);
        System.out.println("Lowest grade: " + grades[0]);
        System.out.println("Highest grade: " + grades[grades.length - 1]);
        
        // Calculate average
        int sum = 0;
        for (int grade : grades) {
            sum += grade;
        }
        double average = (double) sum / grades.length;
        System.out.println("Average grade: " + Math.round(average * 100.0) / 100.0);
        
        // Count occurrences of a grade
        int target = 92;
        int count = 0;
        for (int grade : grades) {
            if (grade == target) count++;
        }
        System.out.println("Students with grade " + target + ": " + count);
    }
}

🧠 Test Your Knowledge

Which property gives you the number of elements in an array?