Groovy – compareTo()

  • Post author:
  • Post category:Groovy
  • Post comments:0 Comments
compareTo method

The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.

Syntax

public int compareTo( NumberSubClass referenceName ) 

Parameters

referenceName – This could be a Byte, Double, Integer, Float, Long or Short.

Return Value

  • If the Integer is equal to the argument then 0 is returned.
  • If the Integer is less than the argument then -1 is returned.
  • If the Integer is greater than the argument then 1 is returned.

Example

Following is an example of the usage of this method −

class Example { 
   static void main(String[] args) { 
      Integer x = 5;
		
      //Comparison against a Integer of lower value 
      System.out.println(x.compareTo(3));
		
      //Comparison against a Integer of equal value 
      System.out.println(x.compareTo(5)); 
		
      //Comparison against a Integer of higher value 
      System.out.println(x.compareTo(8)); 
   } 
} 

When we run the above program, we will get the following result −

1 
0 
-1 

Previous Page:-Click Here

Leave a Reply