Groovy - Arithmetic Operators
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 |
Example - Use of arithmetic operators
In this example, we're creating two variables x and y and using arithmatic operators. We've performed addition, subtraction, multiplication and division operations and printed the results.
Example.groovy
class Example {
static void main(String[] args) {
// Initializing 3 variables
def x = 5;
def y = 10;
//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(y/x);
}
}
Output
When we run the above program, we will get the following result.
15 -5 50 2
Example - Use of modulus operators
In this example, we're creating three variables x,y and z and using arithmatic operator %. We've performed Modulus operations between their values.
Example.groovy
class Example {
static void main(String[] args) {
// Initializing 3 variables
def x = 10;
def y = 20;
def z = 25;
// Performing modulus of operands
println(y % x);
// Performing modulus of another operands
println(z % x);
}
}
Output
When we run the above program, we will get the following result.
0 5
Example - Use of pre and post operators
In this example, we're creating two variables x and y and using arithmatic operators. We've performed post increment, pre increment, post decrement and post increment operations and printed the results.
Example.groovy
class Example {
static void main(String[] args) {
// Initializing 3 variables
def x = 10;
def y = 25;
// Performing post increment
println( x++ );
// Performing post decrement
println( x-- );
// Check the difference in y++ and ++y
println(y++);
println(++y);
}
}
Output
When we run the above program, we will get the following result.
10 11 25 27