Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - 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 - Comparing Integers

Following is an example of the usage of compareTo() method to compare integers −

Example.groovy

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

Output

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

1 
0 
-1 

Example - Comparing Doubles

Following is an example of the usage of compareTo() method to compare doubles −

Example.groovy

class Example { 
   static void main(String[] args) { 
      Double x = 5.0;
		
      // Comparison against a Double of lower value 
      println(x.compareTo(3.0));
		
      // Comparison against a Double of equal value 
      println(x.compareTo(5.0)); 
		
      // Comparison against a Double of higher value 
      println(x.compareTo(8.0)); 
   } 
} 

Output

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

1 
0 
-1 

Example - Comparing Longs

Following is an example of the usage of compareTo() method to compare long values −

Example.groovy

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

Output

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

1 
0 
-1 
groovy_numbers.htm
Advertisements