Groovy – Arithmetic Operators

  • Post author:
  • Post category:Groovy
  • Post comments:1 Comment
Arithmetic operators

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

OperatorDescriptionExample
+Addition of two operands1 + 2 will give 3
Subtracts second operand from the first2 − 1 will give 1
*Multiplication of both operands2 * 2 will give 4
/Division of numerator by denominator3 / 2 will give 1.5
%Modulus Operator and remainder of after an integer/float division3 % 2 will give 1
++Incremental operators used to increment the value of an operand by 1int x = 5;x++;x will give 6
Incremental operators used to decrement the value of an operand by 1int 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

Previous Page:-Click Here

This Post Has One Comment

Leave a Reply