Logical Operators

4 min read ·

Logical operators are used to combine multiple conditions.
They work only with boolean expressions and return either true or false.
These operators are commonly used in decision making statements like if, while and for.

Logical Operators Table

OperatorNameDescriptionExampleResult
&&Logical ANDReturns true if both conditions are truetrue && truetrue
&&Logical ANDReturns false if any condition is falsetrue && falsefalse
||Logical ORReturns true if at least one is truetrue || falsetrue
||Logical ORReturns false if both are falsefalse || falsefalse
!Logical NOTReverses boolean value!truefalse
!Logical NOTReverses boolean value!falsetrue

1 Logical AND Operator &&

Returns true only when both conditions are true.

Complete Truth Table

Condition 1Condition 2Result
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

Example


2 Logical OR Operator ||

Returns true if at least one condition is true.

Complete Truth Table

Condition 1Condition 2Result
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

Example


3 Logical NOT Operator !

Reverses the boolean value.

Complete Truth Table

Original ValueResult After !
truefalse
falsetrue

Example


Combining Logical Operators

Multiple logical operators can be used in one condition.

Short Circuit Concept

Java uses short circuit evaluation.
For AND operator If first condition is false second condition will not execute.
For OR operator If first condition is true second condition will not execute.

Example

Output Value of a: 5
Second condition did not execute because first condition was false.

Caution

Logical operators work only with boolean expressions. Do not use numeric values directly like 1 or 0.


Practice Exercise

  1. Write a program to check if a number is between 20 and 60
  2. Create a program to check if a user can login using username and password
  3. Check if a student passed using marks or grace marks
  4. Reverse a boolean value using logical NOT and print result