Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Charset compareTo() method in Java with Examples
Next article icon

Java Arrays compare() Method with Examples

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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));     } } 

Output
0 

Explanation: The desired output is 0, because we are given two integer arrays with the same numbers and size.

Table of Content

  • Syntax of Array compare() Method
  • Examples of Arrays compare() Method with Different Data Types
    • Comparing Two Integer Arrays
    • Comparing Two Float Arrays

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));      } } 

Output
1 

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));     } } 

Output
-1 

Explanation: The result is -1 in output because arr1 is lexicographically less than arr2.


Next Article
Charset compareTo() method in Java with Examples

G

goutamverma84009
Improve
Article Tags :
  • Java
  • Java-Arrays
  • Java-Functions
Practice Tags :
  • Java

Similar Reads

  • Java Guava | Chars.compare() method with Examples
    Chars.compare() method of Guava's Chars Class is used to compare the two specified char values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compa
    2 min read
  • Byte compare() method in Java with examples
    The compare() method of Byte class is a built in method in Java which is used to compare two byte values. Syntax Byte.compare(byte a, byte b) Parameters: It takes two byte value 'a' and 'b' as input in the parameters which are to be compared. Return Value: It returns an int value. It returns: 0 if '
    2 min read
  • Charset compareTo() method in Java with Examples
    The compareTo() method is a built-in method of the java.nio.charset compares two charsets with each other. A comparison is done by their canonical names, without regard to case. Syntax: public final int compareTo?(Charset second) Parameters: The function accepts a single mandatory parameter second w
    1 min read
  • Java File Class compareTo() Method with Examples
    The compareTo() function compares two pathnames lexicographically. In Java, the method may be used to sort files. This type of activity is dependent on the system on which JVM is installed. When comparing pathnames on Unix systems, the alphabetic case matters, while it doesn't on Windows. Syntax: pu
    1 min read
  • Byte compareTo() method in Java with examples
    The compareTo() method of Byte class is a built in method in Java which is used to compare the given Byte type object with the instance of Byte invoking the compareTo() method. Syntax ByteObject.compareTo(Byte a) Parameters: It takes a Byte type object a as input which is to be compared with the ins
    2 min read
  • Boolean compare() method in Java with Examples
    The compare() method of Boolean class is a built in method in Java which is used to compare two boolean values. It is a static method, so it can be called without creating any object of the Boolean class i.e. directly using the class name. Syntax: Boolean.compare(boolean a, boolean b) Parameters: It
    2 min read
  • Calendar compareTo() Method in Java with Examples
    The add(Calendar Calendar2) method of Calendar class is used to compare the time values or the millisecond offsets of this Calendar object with the passed Calendar object. Syntax: public int compareTo(Calendar Calendar2) Parameters: The method takes one parameter Calendar2 of Calendar object type an
    2 min read
  • Java Guava | Booleans.compare() method with Examples
    The compare() method of Booleans Class in the Guava library is used to compare the two specified boolean values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public
    2 min read
  • Boolean compareTo() method in Java with examples
    The compareTo() method of Boolean class is a built in method in Java which is used to compare the given Boolean instance with the current instance. Syntax: BooleanObject.compareTo(Boolean a) Parameters: It takes a Boolean value a as parameter which is to be compared with the current instance. Return
    2 min read
  • Java String compareTo() Method with Examples
    Strings in Java are objects that are supported internally by an array only which means contiguous allocation of memory for characters. Please note that strings are immutable in Java which means once we create a String object and assign some values to it, we cannot change the content. However, we can
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences