VOOZH about

URL: https://www.geeksforgeeks.org/java/bytebuffer-compareto-method-in-java-with-examples/

⇱ ByteBuffer compareTo() method in Java With Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer compareTo() method in Java With Examples

Last Updated : 6 Jun, 2021

The compareTo() method of java.nio.ByteBuffer class is used to compare one buffer to another. 
Two byte buffers are compared by comparing their sequences of remaining elements lexicographically, without regard to the starting position of each sequence within its corresponding buffer. Pairs of byte elements are compared as if by invoking Byte.compare(byte, byte).
A byte buffer is not comparable to any other type of object.
Syntax : 
 

public int compareTo(ByteBuffer that)


Parameter: This method takes a ByteBuffer object as a parameter with which this buffer will be compared.
Return Value: This method returns a negative integer, zero, or a positive integer as this buffer is less than, equal to, or greater than the given buffer.
Below are the examples to illustrate the compareTo() method:
Examples 1: When both ByteBuffer are equal. 
 


Output: 
ByteBuffer bb: [20, 30, 40]
ByteBuffer bb1: [20, 30, 40]

both buffer are lexicographically equal

 

Examples 2: When this ByteBuffer is greater than the passed ByteBuffer 
 


Output: 
ByteBuffer bb: [30, 30, 40]
ByteBuffer bb1: [20, 30, 40]

bb is lexicographically greater than bb1

 

Examples 3: When this ByteBuffer is less than the passed ByteBuffer 
 


Output: 
ByteBuffer bb: [20, 30, 40]
ByteBuffer bb1: [40, 30, 40]

bb is lexicographically less than bb1

 
Comment