Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

byte
compare
java
communitycreator

What is the Byte.compare method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The static method compare of the Byte class is used to compare two byte values.

Syntax


public static int compare(byte x, byte y);

Returns

This method returns:

  • 0 if both the values are the same.
  • A value less than zero, if the x < y.
  • A value greater than zero, if the x > y.
Byte.compare(x,y)

Case

Return Value

x == y

0

x < y

< 0

x > y

> 0

Code

class ByteCompare {
public static void main( String args[] ) {
byte ten = 10;
byte twenty = 20;
System.out.println("ten, ten : " + Byte.compare(ten, ten));
System.out.println("twenty, twenty : " + Byte.compare(twenty, twenty));
System.out.println("ten, twenty : " + Byte.compare(ten, twenty));
System.out.println("twenty, ten : " + Byte.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two byte variables:
ten = 10;
twenty = 20;
  • We used the compare method of the Byte class to compare the byte values. First, we compared the same values:
ten, ten => 0
twenty, twenty => 0

The compare method returns 0 if both the comparing values are the same.

  • Then, we compared ten with twenty:
compare(ten, twenty);

The compare method returns values < 0 if the first value is less than the second value.

  • Then, we compared twenty with ten:
compare(twenty, ten);

The compare method returns values > 0 if the first value is greater than the second value.

RELATED TAGS

byte
compare
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring