Utilities: Arrays.compare orders two arrays element by element

Arrays.compare performs a lexicographic comparison, returning a negative, zero or positive result based on the first differing element, or on length if one array is a prefix of the other.

Code
int[] a = {1, 2, 3};
int[] b = {1, 2, 4};
int[] shorter = {1, 2};
System.out.println("a vs b: " + Arrays.compare(a, b));
System.out.println("b vs a: " + Arrays.compare(b, a));
System.out.println("shorter vs a: " + Arrays.compare(shorter, a));
Output
a vs b: -1
b vs a: 1
shorter vs a: -1
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms