Java Arrays Class Methods Tutorial with Examples

The Arrays class in Java provides various static methods for manipulating arrays (such as sorting, searching, filling, copying, etc.). This tutorial will cover all methods of the Arrays utility class with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. Arrays Methods
    • sort()
    • binarySearch()
    • equals()
    • fill()
    • copyOf()
    • copyOfRange()
    • toString()
    • asList()
    • parallelSort()
    • setAll()
    • stream()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

The Arrays class in Java is a part of the java.util package and provides various static methods for manipulating arrays. It includes methods for sorting, searching, comparing, filling, and converting arrays.

2. Key Points

  • Arrays class contains static methods only.
  • It provides utility methods for array operations.
  • Methods can perform operations such as sorting, searching, filling, copying, and converting arrays.
  • It includes methods for parallel sorting and working with streams.

3. Arrays Methods

3.1. sort()

The sort() method sorts the specified array into ascending order.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1, 2};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[1, 2, 3, 5, 8]

3.2. binarySearch()

The binarySearch() method searches the specified array for the specified value using the binary search algorithm. The array must be sorted before calling this method.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 5, 8};
        int index = Arrays.binarySearch(numbers, 5);
        System.out.println("Index of 5: " + index);
    }
}

Output:

Index of 5: 3

3.3. equals()

The equals() method returns true if the two specified arrays are equal to one another.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 5, 8};
        int[] numbers2 = {1, 2, 3, 5, 8};
        boolean isEqual = Arrays.equals(numbers1, numbers2);
        System.out.println("Arrays are equal: " + isEqual);
    }
}

Output:

Arrays are equal: true

3.4. fill()

The fill() method assigns the specified value to each element of the specified array.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Arrays.fill(numbers, 9);
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[9, 9, 9, 9, 9]

3.5. copyOf()

The copyOf() method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int[] newNumbers = Arrays.copyOf(numbers, 3);
        System.out.println(Arrays.toString(newNumbers));
    }
}

Output:

[1, 2, 3]

3.6. copyOfRange()

The copyOfRange() method copies the specified range of the specified array into a new array.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int[] newNumbers = Arrays.copyOfRange(numbers, 1, 4);
        System.out.println(Arrays.toString(newNumbers));
    }
}

Output:

[2, 3, 4]

3.7. toString()

The toString() method returns a string representation of the contents of the specified array.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        String arrayString = Arrays.toString(numbers);
        System.out.println(arrayString);
    }
}

Output:

[1, 2, 3, 4, 5]

3.8. asList()

The asList() method returns a fixed-size list backed by the specified array.

Example:

import java.util.Arrays;
import java.util.List;

public class ArraysExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Mango", "Banana"};
        List<String> fruitList = Arrays.asList(fruits);
        System.out.println(fruitList);
    }
}

Output:

[Apple, Mango, Banana]

3.9. parallelSort()

The parallelSort() method sorts the specified array into ascending numerical order using the specified parallel sorting algorithm.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1, 2};
        Arrays.parallelSort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[1, 2, 3, 5, 8]

3.10. setAll()

The setAll() method sets all elements of the specified array, using the provided generator function to compute each element.

Example:

import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Arrays.setAll(numbers, i -> i + 1);
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[1, 2, 3, 4, 5]

3.11. stream()

The stream() method returns a sequential Stream with the specified array as its source.

Example:

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        Arrays.stream(numbers).forEach(System.out::println);
    }
}

Output:

1
2
3
4
5

4. Use Cases

  • Sorting and Searching: Sorting arrays and performing binary search operations.
  • Data Manipulation: Filling, copying, and comparing arrays.
  • Conversion: Converting arrays to lists and strings.
  • Parallel Operations: Using parallel sorting for large arrays.
  • Stream Processing: Working with streams for functional programming.

5. Best Practices

  • Ensure array is sorted: When using binarySearch(), ensure the array is sorted.
  • Avoid modifying arrays returned by asList(): The list returned by asList() is fixed-size.
  • Use parallelSort() for large arrays: For better performance on large arrays, use parallelSort().

6. Performance Considerations

  • Algorithmic complexity: Understand the algorithmic complexity of operations like sort, binary search, and fill.
  • Parallel operations overhead: Be aware of the overhead associated with parallel sorting.

7. Real-time Example with CRUD Operations

Managing an Inventory System:

Product.java:

public class Product {
    private String name;
    private int quantity;

    public Product(String name, int quantity) {
        this.name = name;
        this.quantity = quantity;
    }

    public String getName() {
        return name;
    }

    public int getQuantity() {
        return quantity;
    }

    @Override
    public String toString() {
        return "Product{name='" + name + "', quantity=" + quantity + "}";
    }
}

Main.java:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Product[] products = {
            new Product("Laptop", 10),
            new Product("Mobile", 20),
            new Product("Tablet", 15)
        };

        // Create
        products = Arrays.copyOf(products, products.length + 1);
        products[products.length - 1] = new Product("Smartwatch", 5);

        // Read


 System.out.println("Products:");
        Arrays.stream(products).forEach(System.out::println);

        // Update
        products[1] = new Product("Mobile", 25);
        System.out.println("After Update:");
        Arrays.stream(products).forEach(System.out::println);

        // Delete
        products = Arrays.stream(products)
                         .filter(product -> !"Laptop".equals(product.getName()))
                         .toArray(Product[]::new);
        System.out.println("After Deletion:");
        Arrays.stream(products).forEach(System.out::println);

        // Sort
        Arrays.sort(products, (p1, p2) -> p1.getName().compareTo(p2.getName()));
        System.out.println("After Sorting:");
        Arrays.stream(products).forEach(System.out::println);
    }
}

Output:

Products:
Product{name='Laptop', quantity=10}
Product{name='Mobile', quantity=20}
Product{name='Tablet', quantity=15}
Product{name='Smartwatch', quantity=5}
After Update:
Product{name='Laptop', quantity=10}
Product{name='Mobile', quantity=25}
Product{name='Tablet', quantity=15}
Product{name='Smartwatch', quantity=5}
After Deletion:
Product{name='Mobile', quantity=25}
Product{name='Tablet', quantity=15}
Product{name='Smartwatch', quantity=5}
After Sorting:
Product{name='Mobile', quantity=25}
Product{name='Smartwatch', quantity=5}
Product{name='Tablet', quantity=15}

8. Conclusion

The Arrays utility class in Java provides a comprehensive set of static methods for performing common array operations. By understanding its methods, use cases, and best practices, you can effectively utilize the Arrays class in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments