A blog for computer science passionates.

Thursday, 5 March 2020

Java: Operators Part-3 if((Boolean Logical & Shortcircuit Operators)==true)

Hello Friends!!!
In the previous article, we have seen bitwise ☺perators. Let's start with the boolean logical operator. logical operators work on boolean operands(variables & values). It is a binary operator.


Logical Operators
&
Boolean Logical And
a&b
|
Boolean Logical Or
a|b
^
Boolean Logical Ex-Or (XOR)
a^b
&&
Logical AND
a&&b
||
Logical OR
a||b
!
Logical Unary NOT
!a

These are the Logical Operators. It gives the values either true or false. The &, |, ^,! return the same values as we have already seen in bitwise operators but here is we get the answer is either true or false only. see the below figure.
Fig. Truth Table of Boolean Logical Operators

So these are the boolean logical operators but if we use && or || then it becomes short-circuit logical operators. Java supports this operator these operators are another form of boolean logical operator. As you can see in the truth table The OR operator (||) returns true when A is true no matter what is the value of B. Same with AND operator (&&) returns false when A is false no matter what is the value of B. Java does not work on second expression i.e. right-hand side expression.
Let's understand with an example
if(b!=0 && a/b==0)
the above expression saves our code from the causing run-time exception. if b does not equal to 0 returns true then only a/b will work.
Let's try with this expression,
if(args.length!=0 && args[0].equals("Hello"))

That's it for this article, in the next article we will learn new operators till then
Happy C☺ding... :)

No comments:

Post a Comment