Home »
Java programming language
Java - Byte Class compareTo() Method
Short class compareTo() method: Here, we are going to learn about the compareTo() method of Short class with its syntax and example.
By Preeti Jain Last updated : March 18, 2024
Short class compareTo() method
- compareTo() method is available in java.lang package.
- compareTo() method is used to check equality or inequality for this Byte object against the given Byte object mathematically or in other words, we can say this method is used to compare two Byte objects.
- compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- compareTo() method does not throw an exception at the time of comparing Byte object.
Syntax
public int compareTo(Byte value2);
Parameter
- Byte value2 – represents the Byte object to compare with.
Return Value
The return type of this method is int, it returns an integer value based on the following cases,
- It returns 0, if value1 is mathematically equal to value2.
- It returns the value < 0, if value1 is mathematically less than value2.
- It returns the value > 0, if value1 is mathematically greater than value2.
Example
// Java program to demonstrate the example
// of compareTo(Byte value2) method of Byte class
public class CompareToOfByteClass {
public static void main(String[] args) {
// Variables initialization
byte b1 = 10;
byte b2 = 20;
// Byte instance
Byte value1 = new Byte(b1);
Byte value2 = new Byte(b2);
// It compare two Byte objects and placed the result
// in another variable (compare) of integer type
int compare = value1.compareTo(value2);
// Display result
System.out.println("value1.compareTo(value2): " + compare);
System.out.println();
if (compare == 0)
System.out.println("value1 is equal to value2");
else if (compare < 0)
System.out.println("value1 is less than value2");
else
System.out.println("value1 is greater than value2");
}
}
Output
value1.compareTo(value2): -10
value1 is less than value2