BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Arrays Methods

Last Updated: June 3, 2024 by Chaitanya Singh | Filed Under: java

In Java, the Arrays class belong to java.util.Arrays. This class provides several useful methods that we can use to work with arrays more efficiently. In this guide, we will discuss some of the commonly used methods of Java Arrays class with examples.

Commonly Used Methods in java.util.Arrays

1. Sorting Arrays

Arrays.sort(): This methods sorts the given array in ascending order.

int[] numbers = {5, 2, 8, 7, 11};
Arrays.sort(numbers);
// numbers array after sorting [2, 5, 7, 8, 11]

Arrays.sort(array, fromIndex, toIndex): This method sorts the array between the specified indexes. In this method, we provide fromIndex and toIndex along with the array name which we want to sort. Note that fromIndex is inclusive while toIndex is exclusive.

Arrays.sort(numbers, 1, 4);
// Only elements from index 1 to 3 are sorted

2. Binary Search

Arrays.binarySearch(): This method uses binary search algorithm to search specified element in the array. As per the rules of binary search algorithm, the array must be sorted.

int index = Arrays.binarySearch(numbers, 7);
// Returns the index of the value 7 in the sorted array

3. Filling Arrays

Arrays.fill(): As the name suggests, this methods fills the entire array with the specified element.

int[] numbers = new int[5];
Arrays.fill(numbers, 10);
// numbers array elements are [10, 10, 10, 10, 10]

Arrays.fill(array, fromIndex, toIndex, value): It fills the array with the specified element between specified indexes. The fromIndex is inclusive and toIndex is exclusive.

// This will fill the array with element 5
// from index 1 to index 3 (4 is exclusive)
Arrays.fill(numbers, 1, 4, 5);
// numbers array elements are [10, 5, 5, 5, 10]

4. Comparing Arrays

Arrays.equals(): This method takes two array references as arguments and returns true if they are equal else it returns false.

int[] array1 = {1, 2, 3, 4};
int[] array2 = {1, 2, 3, 4};
boolean areEqual = Arrays.equals(array1, array2); // true

Arrays.deepEquals(): This method is used for nested arrays. It returns true if the two specified arrays are deeply equal to one another.

int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
boolean areEqual = Arrays.deepEquals(array1, array2); // true

Arrays.mismatch(array1, array2): It compares two specified arrays and returns the first index where two arrays differ. If both the arrays are equal, it returns -1.

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1, 2, 0, 4, 5};
int mismatchIndex = Arrays.mismatch(array1, array2);
System.out.println("Mismatch index: " + mismatchIndex);
// Output: Mismatch index: 2

5. Copying Arrays

Arrays.copyOf(originalArray, newLength): This method copies the specified array into the given array. It also takes array length as an argument, if the specified length is less then the original array length then it truncates the remaining elements, however if the length is greater than the original array length then it fills the remaining positions with default values as shown below.

int[] originalArray = {10, 20, 30, 40, 50};

int[] copiedArray = Arrays.copyOf(originalArray, 3);
// copiedArray elements are [10, 20, 30]

int[] copiedArray = Arrays.copyOf(originalArray, 7);
// copiedArray elements are [10, 20, 30, 40, 50, 0, 0]

Arrays.copyOfRange(originalArray, fromIndex, toIndex): It copies the elements between specified indexes to the new array. Index fromIndex is inclusive and toIndex is exclusive.

int[] originalArray = {10, 20, 30, 40, 50};
int[] copiedArray = Arrays.copyOfRange(originalArray, 1, 4);
// copiedArray elements are [10, 20, 30]

6. Converting Arrays to String

Arrays.toString(): This method returns a string representation of array elements

char[] array = {'h', 'e', 'l', 'l', 'o'};
String arrayString = Arrays.toString(array);
// arrayString is "hello"

7. Parallel Sorting

Arrays.parallelSort(): This method sorts the specified array into ascending order using parallel sorting.

int[] array = {10, 50, 30, 40, 20};
Arrays.parallelSort(array);
// array elements are [10, 20, 30, 40, 50]

Usage Example of various Arrays Methods

Here’s a complete example that demonstrates the use of several of these methods:

import java.util.Arrays;

public class ArrayMethodsExample {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 7, 1};

// Sorting
Arrays.sort(numbers);
System.out.println("Sorted: " + Arrays.toString(numbers));

// Since, the array is now sorted, we can use Binary Search
int index = Arrays.binarySearch(numbers, 7);
System.out.println("Index of element 7: " + index);

// Filling entire array with 0's
Arrays.fill(numbers, 0);
System.out.println("Filled: " + Arrays.toString(numbers));

// Copying elements from numbers array to copiedArray with length 3
int[] copiedArray = Arrays.copyOf(numbers, 3);
System.out.println("Copied: " + Arrays.toString(copiedArray));

// Comparing two given arrays
int[] array1 = {1, 2, 3, 44};
int[] array2 = {1, 2, 3, 44};
boolean areEqual = Arrays.equals(array1, array2);
System.out.println("Are equal: " + areEqual);
}
}

Output:

Sorted: [1, 2, 5, 7, 8]
Index of element 7: 3
Filled: [0, 0, 0, 0, 0]
Copied: [0, 0, 0]
Are equal: true

Conclusion

The java.util.Arrays class provides several useful methods for performing various operations on array, such as sort, search, fill, compare, copy etc. Using these methods, you can work with array effectively.

Top Related Articles:

  1. Difference between local, instance and static variables in Java
  2. How to Compile and Run your First Java Program
  3. ArrayList clone() method in Java
  4. Java Scanner class with examples
  5. Convert Integer List to int Array in Java

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap