Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Float.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.

The compare method is a static method of the Float class that is used to compare two float values.

Syntax

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

Parameters

The function takes in two float values as a parameter.

Return value

This method returns:

  • 0 if both the values are the same.

  • A value less than zero if x is less than y.

  • A value greater than zero if the x is greater than y.

Float.compare(x,y)

Case

Return Value

x == y

0

x < y

< 0

x > y

> 0

Code

The example below uses the Float.compare method:

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

Explanation

In the code above:

  • We created two float variables:
ten = 10f;
twenty = 20f;
  • We used the compare method of the Float class to compare the float values.
  • First, we compared the same values:
compare(ten,ten);
compare(twenty, twenty);

  • The compare method returns 0, as both the compared values are the same.

  • Then, we compared ten with twenty:

compare(ten, twenty);
  • The compare method returns a value < 0 because the first value is less than the second value.

  • Then, we compared twenty with ten.

compare(twenty, ten);
  • The compare method returns a value > 0 because the first value is greater than the second value.

RELATED TAGS

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.

Keep Exploring