Java Arrays compare() Method with Examples
Last Updated :
25 Nov, 2024
The Arrays compare() method in Java is a part of the java.util package to compare arrays lexicographically (dictionary order). This method is useful for ordering arrays and different overloads for different types including boolean, byte, char, double, float, int, long, short, and Object arrays.
Example:
Below is a simple example of Arrays.compare() method, where we compare two integer arrays with the same elements.
Java
import java.util.Arrays;
public class ArrayCompare {
public static void main(String[] args)
{
// Initialize two integer array with same elements
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 1, 2, 3, 4 };
// compare arr1 and arr2 using compare() method
// and print the result
System.out.println(
"" + Arrays.compare(arr1, arr2));
}
}
Explanation: The desired output is 0, because we are given two integer arrays with the same numbers and size.
Syntax of Array compare() Method
Arrays.compare(arr1,arr2); // arr1 and arr2 are two arrays
Parameters: The compare()
method accepts two arrays as parameters, with supported data types like String
, Integer
, Float
, Double
, Long
, and others.
Return Type: The return type of this method is an integer.
- It returns positive value, if the first array is lexicographically greater.
- It returns negative value, if the first array is lexicographically lesser.
It returns 0,
if both arrays are equal.
Exceptions: NullPointerException: This exception is thrown, if an array is null when accessed.
Examples of Arrays compare()
Method with Different Data Types
Compare Two Integer Arrays
In this example, we will compare two integer arrays to determine their lexicographical order using the compare()
method from the Arrays
class.
Java
import java.util.Arrays;
public class CompareExample{
public static void main(String[] args)
{
//Initialized two integer array
int[] arr1 ={6, 7, 8, 11, 18, 8, 2, 5};
int[] arr2 ={3, 5, 9, 13, 28, 6, 8, 9};
//compare both integer array using compare method and finally print result
System.out.println(""+ Arrays.compare(arr1,arr2));
}
}
Explanation: Here, the output is 1 because arr1 is lexicographically greater than arr2.
Compare Two Float Arrays
In this example, we will compare two float arrays to assess their lexicographical order using the compare()
method.
Java
import java.util.Arrays;
public class CompareExample{
public static void main(String[] args)
{
// Initialize two float array with element
float[] arr1={5.12f, 8.3f, 9.17f, 2.5f, 8.8f, 5.17f, 4.2f, 7.37f};
float[] arr2={7.12f, 9.3f, 6.17f, 7.5f, 5.8f, 7.17f, 3.2f, 6.37f};
// compare two float array using compare method and finally print result
System.out.println("" + Arrays.compare(arr1, arr2));
}
}
Explanation: The result is -1 in output because arr1 is lexicographically less than arr2.