What is the ByteBuffer compareTo() method in Java?

We can use the compareTo() method of the class java.nio.ByteBuffer to compare two buffers. We compare the two buffers by looking at their sequence of remaining elements lexicographically, without regard to the starting point of the buffers.

The Byte.compare() method compares two bites in the same way.

Declaration

The ByteBuffer.compareTo() method can be declared as follows:

buff1.compareTo(buff2);
  • buff1: The first buffer, to be compared to buff2.
  • buff2: The second buffer, to be compared to buff1.

Return value

The ByteBuffer.compareTo() method returns an integer such that:

  • The return value is a positive integer if buff1 is greater than buff2.
  • The return value is 0 if buff1 is equal to buff2.
  • The return value is a negative integer if buff1 is less than buff2.

Code

Consider the code snippet below, which demonstrates the use of the ByteBuffer.compareTo() method:

import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args) {
int n1 = 5;
int n2 = 4;
try {
ByteBuffer buff1 = ByteBuffer.allocate(n1);
buff1.put((byte)1);
buff1.put((byte)4);
System.out.println("buff1: " + Arrays.toString(buff1.array()));
ByteBuffer buff2 = ByteBuffer.allocate(n2);
buff2.put((byte)3);
buff2.put((byte)4);
System.out.println("buff2: " + Arrays.toString(buff2.array()));
int foo = buff1.compareTo(buff2);
System.out.println("\nbuff1 compareTo to buff2: " + foo);
} catch (IllegalArgumentException e) {
System.out.println("Error!!! IllegalArgumentException");
} catch (ReadOnlyBufferException e) {
System.out.println("Error!!! ReadOnlyBufferException");
}
}
}

Explanation

  • A ByteBuffer buff1 is declared in line 8. Two valuess are written to buff1 in lines 9-10.
  • A ByteBuffer buff2 is declared in line 13. Two valuess are written to buff2 in lines 14-15.
  • The ByteBuffer.compareTo() method is used in line 18 to see if buff1 and buff2 are equal. The ByteBuffer.compareTo() method returns a positive integer, which means that buff1 is greater than buff2.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved