Sunday 13 January 2019

Groovy: Logical Operators


Groovy provides three logical operators, These are &&(AND), || (OR), and !(NOT)

Logical AND is also called Conditional AND
Logical OR is also called Conditional OR

Logical AND, OR are called Short circuit operators, will see why these are called short circuit soon.

Logical AND Operator
Operand1
Operand2
Evaluates To
false
false
false
false
true
false
true
false
false
true
true
true

HelloWorld.groovy
println "false && false : ${false && false}"
println "false && true : ${false && true}"
println "true && false : ${true && false}"
println "true && true : ${true && true}"

Output
false && false : false
false && true : false
true && false : false
true && true : true

Why Logical AND is called short circuit operator
Since if the first statement in the expression evaluates to false, then Groovy won't evaluate the entire expression. So Logical AND is called short circuit AND


HelloWorld.groovy
int a = 10, b=21;a

if( (a>b) && (a++ > b) ){
	println "This statement not evaluated"
}
println "a is not incremented ${a}"

if( (a<b) && (a++ < b) ){
 println "This statement is evaluated"
} 

println "a is incremented ${a}"

Output
a is not incremented 10
This statement is evaluated
a is incremented 11

Observation
In the expression (a>b) && (a++ > b), a>b is false, so && operator won't evaluate second statement in the expression, so a is not incremented.

Logical OR Operator
Logical OR (||) operator returns true if any of the operand evaluates to true, otherwise returns false.
Operand1
Operand2
Evaluates To
false
false
False
false
true
True
true
false
True
true
true
True


HelloWorld.groovy
println "false || false : ${false || false}"
println "false || true : ${false || true}"
println "true || false : ${true || false}"
println "true || true : ${true || true}"

Output
false || false : false
false || true : true
true || false : true
true || true : true

Why Logical OR is called short circuit operator
If the first statement evaluates to true, then Groovy won't evaluates the entire expression. So Logical OR is called short circuit OR


HelloWorld.groovy
a = 10
b=21;

if( (a<b) || (a++ < b) ){
	println "This statement evaluated"
}

println "a is not incremented ${a}"

if( (a>b) || (a++ > b) ){
	println "This statement is evaluated"
} 

println "a is incremented ${a}"

Output
This statement evaluated
a is not incremented 10
a is incremented 11

Logical (!)NOT operator
If the operand is false, ! Operator evaluates it to true
If the operand is true, ! Operator evaluates it to false

Operand
Evaluates To
false
true
true
false


HelloWorld.groovy
a = false
b = true

println "a : ${a}"
println "!a : ${!a}"
println "b : ${b}"
println "!b : ${!b}"

Output
a : false
!a : true
b : true
!b : false


Previous                                                 Next                                                 Home

No comments:

Post a Comment