Friday 26 July 2019

Processing: Logical Operators


Processing supports 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
true
true
true
true
false
false
false
true
false
false
false
false

Operators.pde
boolean operand1 = true;
boolean operand2 = true;
println((operand1 && operand2)); 

operand1 = true;
operand2 = false;
println((operand1 && operand2)); 

operand1 = false;
operand2 = true;
println((operand1 && operand2)); 

operand1 = false;
operand2 = false;
println((operand1 && operand2));

Output
true
false
false
false

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


Operators.pde
int a = 10, b=21;

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 not incremented " + a);

Output
a is not incremented 10
This statement is evaluated
a is not 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
Operand1
Operand2
Evaluates To
true
true
true
true
false
false
false
true
false
false
false
false

As shown in the above table, || operator returns true if any of the operand evaluates to true, otherwise returns false.


Operators.pde
boolean operand1 = true;
boolean operand2 = true;
println((operand1 || operand2)); 

operand1 = true;
operand2 = false;
println((operand1 || operand2)); 

operand1 = false;
operand2 = true;
println((operand1 || operand2)); 

operand1 = false;
operand2 = false;
println((operand1 || operand2));

Output
true
true
true
false

Why Logical OR is called short circuit operator
Since if the first statement evaluates to true, then Processing won't evaluate the entire expression. So Logical OR is called short circuit OR


Operators.pde
int 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
Operand
Evaluates to
true
false
false
true


Operators.pde

boolean a = true;
println((!a));

a = false;
println((!a));

Output
false
true



Previous                                                    Next                                                    Home

No comments:

Post a Comment