Operators in Groovy are symbols or keywords that are used to perform specific operations on variables or values. Expressions are combinations of variables, values, and operators that produce a resulting value. Here are some of the most commonly used operators and expressions in Groovy:
Arithmetic Operators:
– Addition (+): Adds two values together.
– Subtraction (-): Subtracts one value from another.
– Multiplication (*): Multiplies two values together.
– Division (/): Divides one value by another.
– Modulus (%): Returns the remainder of a division.
Relational Operators:
– Equal to (==): Returns true if two values are equal.
– Not equal to (!=): Returns true if two values are not equal.
– Greater than (>): Returns true if one value is greater than another.
– Less than (<): Returns true if one value is less than another.
- Greater than or equal to (>=): Returns true if one value is greater than or equal to another.
– Less than or equal to (<=): Returns true if one value is less than or equal to another.
Logical Operators:
- AND (&&): Returns true if both values are true.
- OR (||): Returns true if either value is true.
- NOT (!): Returns the opposite boolean value of the operand.
Assignment Operators:
- Assignment (=): Assigns a value to a variable.
- Addition assignment (+=): Adds a value to a variable and assigns the result to the variable.
- Subtraction assignment(-=): Subtracts a value from a variable and assigns the result to the variable.
- Multiplication assignment (*=): Multiplies a variable by a value and assigns the result to the variable.
- Division assignment (/=): Divides a variable by a value and assigns the result to the variable.
- Modulus assignment (%=): Computes the modulus of a variable and a value, and assigns the result to the variable.
Here are some examples of using operators and expressions in Groovy:
Arithmetic Operators:
def x = 10 def y = 5 def z = x + y // z equals 15 def a = x - y // a equals 5 def b = x * y // b equals 50 def c = x / y // c equals 2 def d = x % y // d equals 0
Relational Operators:
def age = 30 def isAdult = age >= 18 // isAdult equals true def isTeenager = age >= 13 && age <= 19 // isTeenager equals true def isSenior = age >= 65 // isSenior equals false
Logical Operators:
def isTrue = true def isFalse = false def andResult = isTrue && isFalse // andResult equals false def orResult = isTrue || isFalse // orResult equals true def notResult = !isTrue // notResult equalsfalse
Assignment Operators:
def count = 10 count += 5 // count now equals 15 count -= 3 // count now equals 12 count *= 2 // count now equals 24 count /= 3 // count now equals 8 count %= 5 // count now equals 3
Expressions can be composed of one or more operators and values. For example:
def a = 5 def b = 10 def c = (a + b) * 2 // c equals 30