Java Logical Operators with Examples
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.
Here are a few types:
- Arithmetic Operators
- Unary Operators
- Assignment Operator
- Relational Operators
- Logical Operators
- Ternary Operator
- Bitwise Operators
- Shift Operators
This article explains all that one needs to know regarding the Logical Operators.
These operators are used to perform logical “AND”, “OR” and “NOT” operation, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Let’s look at each of the logical operators in a detailed manner:
1. ‘Logical AND’ Operator(&&):
This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. For example, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).
condition1 && condition2
a = 10, b = 20, c = 20 condition1: a < b condition2: b == c if(condition1 && condition2) d = a+b+c // Since both the conditions are true d = 50.
Var1 = 10 Var2 = 20 Var3 = 20 The sum is: 50
Now in the below example, we can see the short-circuiting effect. Here when the execution reaches to if statement, the first condition inside the if statement is false and so the second condition is never checked. Thus the ++b(pre-increment of b) never happens and b remains unchanged.
2. ‘Logical OR’ Operator(||):
This operator returns true when one of the two conditions under consideration is satisfied or is true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.
condition1 || condition2
a = 10, b = 20, c = 20 condition1: a < b condition2: b > c if(condition1 || condition2) d = a+b+c // Since one of the condition is true d = 50.
Var1 = 10 Var2 = 1 Var3 = 10 Var4 = 30 One or both the conditions are true
3. ‘Logical NOT’ Operator(!):
Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false.
a = 10, b = 20 !(a<b) // returns false !(a>b) // returns true
Var1 = 10 Var2 = 1 !(a < b) = true !(a > b) = false