Java.lang Package Classes

Java Byte - compareTo() Method



The java.lang.Byte.compareTo() method is used to compare two Byte objects numerically.

Syntax

public int compareTo(Byte anotherByte)

Parameters

anotherByte Specify the Byte to be compared.

Return Value

Returns the value 0 if this Byte is equal to the argument Byte; a value less than 0 if this Byte is numerically less than the argument Byte; and a value greater than 0 if this Byte is numerically greater than the argument Byte (signed comparison).

Exception

NA.

Example:

In the example below, the java.lang.Byte.compareTo() method is used to compare given Byte objects.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating Byte objects
    Byte val1 = 5;
    Byte val2 = 5;
    Byte val3 = -5;

    //comparing Byte objects 
    System.out.println("comparing val1 with val2: " + val1.compareTo(val2)); 
    System.out.println("comparing val1 with val3: " + val1.compareTo(val3)); 
    System.out.println("comparing val3 with val1: " + val3.compareTo(val1));    
  }
}

The output of the above code will be:

comparing val1 with val2: 0
comparing val1 with val3: 10
comparing val3 with val1: -10

❮ Java.lang - Byte