Groovy - Arithmetic Operators


Advertisements

The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −

Operator Description Example
+ Addition of two operands 1 + 2 will give 3
Subtracts second operand from the first 2 − 1 will give 1
* Multiplication of both operands 2 * 2 will give 4
/ Division of numerator by denominator 3 / 2 will give 1.5
% Modulus Operator and remainder of after an integer/float division 3 % 2 will give 1
++ Incremental operators used to increment the value of an operand by 1

int x = 5;

x++;

x will give 6

-- Incremental operators used to decrement the value of an operand by 1

int x = 5;

x--;

x will give 4

The following code snippet shows how the various operators can be used.

class Example { 
   static void main(String[] args) { 
      // Initializing 3 variables 
      def x = 5; 
      def y = 10; 
      def z = 8; 
		
      //Performing addition of 2 operands 
      println(x+y); 
		
      //Subtracts second operand from the first 
      println(x-y); 
		
      //Multiplication of both operands 
      println(x*y);
		
      //Division of numerator by denominator 
      println(z/x); 
		
      //Modulus Operator and remainder of after an integer/float division 
      println(z%x); 
		
      //Incremental operator 
      println(x++); 
		
      //Decrementing operator 
      println(x--);  
   } 
} 

When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above.

15 
-5 
50 
1.6 
3 
5 
6
groovy_operators.htm
Advertisements