Java.lang Package Classes

Java Byte - compare() Method



The java.lang.Byte.compare() method is used to compare two byte values numerically. The value returned is identical to what would be returned by: Byte.valueOf(x).compareTo(Byte.valueOf(y)).

Syntax

public static int compare(byte x,
                          byte y)

Parameters

x Specify the first byte to compare.
y Specify the second byte to compare.

Return Value

Returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.

Exception

NA.

Example:

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

import java.lang.*;

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

    //comparing byte values 
    System.out.println("comparing val1 and val2: " + Byte.compare(val1, val2)); 
    System.out.println("comparing val1 and val3: " + Byte.compare(val1, val3)); 
    System.out.println("comparing val3 and val1: " + Byte.compare(val3, val1));    
  }
}

The output of the above code will be:

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

❮ Java.lang - Byte

5