GFG App
Open App
Browser
Continue

# Java Logical Operators with Examples

Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, 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, while using AND operator, the second condition is not evaluated if the first one is false. Whereas while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND and OR operators have a short-circuiting effect. Used extensively to test for several conditions for making a decision.

1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
2. OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t]
3. NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

## Example For Logical Operator in Java

Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for all the situations.

```a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a
Condition 2: c > b

Output: True [Both Conditions are true]

For OR Operator:

Condition 1: c > a
Condition 2: c > b

Output: True [One of the Condition if true]

For NOT Operator:
Condition 1: c > a
Condition 2: c > b

Output: False [Because the result was true and NOT operator did it's opposite]```

## 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. In Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).

Syntax:

`condition1 && condition2`

Illustration:

```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.```

Example

## Java

 `// Java code to illustrate` `// logical AND operator`   `import` `java.io.*;`   `class` `Logical {` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// initializing variables` `        ``int` `a = ``10``, b = ``20``, c = ``20``, d = ``0``;`   `        ``// Displaying a, b, c` `        ``System.out.println(``"Var1 = "` `+ a);` `        ``System.out.println(``"Var2 = "` `+ b);` `        ``System.out.println(``"Var3 = "` `+ c);`   `        ``// using logical AND to verify` `        ``// two constraints` `        ``if` `((a < b) && (b == c)) {` `            ``d = a + b + c;` `            ``System.out.println(``"The sum is: "` `+ d);` `        ``}` `        ``else` `            ``System.out.println(``"False conditions"``);` `    ``}` `}`

Output

```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.

Example:

## Java

 `import` `java.io.*;`   `class` `shortCircuiting {` `    ``public` `static` `void` `main(String[] args)` `    ``{`   `        ``// initializing variables` `        ``int` `a = ``10``, b = ``20``, c = ``15``;`   `        ``// displaying b` `        ``System.out.println(``"Value of b : "` `+ b);`   `        ``// Using logical AND` `        ``// Short-Circuiting effect as the first condition is` `        ``// false so the second condition is never reached` `        ``// and so ++b(pre increment) doesn't take place and` `        ``// value of b remains unchanged` `        ``if` `((a > c) && (++b > c)) {` `            ``System.out.println(``"Inside if block"``);` `        ``}`   `        ``// displaying b` `        ``System.out.println(``"Value of b : "` `+ b);` `    ``}` `}`

Output:

The output of AND Operator

## 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.

Syntax:

`condition1 || condition2`

Example:

```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.```

## Java

 `// Java code to illustrate` `// logical OR operator`   `import` `java.io.*;`   `class` `Logical {` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// initializing variables` `        ``int` `a = ``10``, b = ``1``, c = ``10``, d = ``30``;`   `        ``// Displaying a, b, c` `        ``System.out.println(``"Var1 = "` `+ a);` `        ``System.out.println(``"Var2 = "` `+ b);` `        ``System.out.println(``"Var3 = "` `+ c);` `        ``System.out.println(``"Var4 = "` `+ d);`   `        ``// using logical OR to verify` `        ``// two constraints` `        ``if` `(a > b || c == d)` `            ``System.out.println(` `                ``"One or both + the conditions are true"``);` `        ``else` `            ``System.out.println(` `                ``"Both the + conditions are false"``);` `    ``}` `}`

Output

```Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true```

Now in the below example, we can see the short-circuiting effect for OR operator. Here when the execution reaches to if statement, the first condition inside the if statement is true and so the second condition is never checked. Thus the ++b (pre-increment of b) never happens and b remains unchanged.

Example

## Java

 `import` `java.io.*;`   `class` `ShortCircuitingInOR {` `    ``public` `static` `void` `main (String[] args) {` `        `  `      ``// initializing variables` `        ``int` `a = ``10``, b = ``20``, c = ``15``;` `        `  `        ``// displaying b` `        ``System.out.println(``"Value of b: "` `+b);` `        `  `        ``// Using logical OR` `        ``// Short-circuiting effect as the first condition is true` `        ``// so the second condition is never reached` `        ``// and so ++b (pre-increment) doesn't take place and ` `        ``// value of b remains unchanged` `        ``if``((a < c) || (++b < c))` `            ``System.out.println(``"Inside if"``);` `        `  `        ``// displaying b` `        ``System.out.println(``"Value of b: "` `+b);` `      `  `    ``}` `}`

Output

```Value of b: 20
Inside if
Value of b: 20```

## 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.

Syntax:

`!(condition)`

Example:

```a = 10, b = 20

!(a<b) // returns false
!(a>b) // returns true```

## Java

 `// Java code to illustrate` `// logical NOT operator` `import` `java.io.*;`   `class` `Logical {` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// initializing variables` `        ``int` `a = ``10``, b = ``1``;`   `        ``// Displaying a, b, c` `        ``System.out.println(``"Var1 = "` `+ a);` `        ``System.out.println(``"Var2 = "` `+ b);`   `        ``// Using logical NOT operator` `        ``System.out.println(``"!(a < b) = "` `+ !(a < b));` `        ``System.out.println(``"!(a > b) = "` `+ !(a > b));` `    ``}` `}`

Output

```Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false```

### 4. Implementing all logical operators on Boolean values (By default values – TRUE or FALSE)

#### Syntax –

``` boolean a = true;
boolean b = false;```

## Java

 `public` `class` `LogicalOperators {` `    ``public` `static` `void` `main(String[] args) {` `        ``boolean` `a = ``true``;` `        ``boolean` `b = ``false``;`   `        ``System.out.println(``"a: "` `+ a);` `        ``System.out.println(``"b: "` `+ b);` `        ``System.out.println(``"a && b: "` `+ (a && b));` `        ``System.out.println(``"a || b: "` `+ (a || b));` `        ``System.out.println(``"!a: "` `+ !a);` `        ``System.out.println(``"!b: "` `+ !b);` `    ``}` `}`

Output

```a: true
b: false
a && b: false
a || b: true
!a: false
!b: true```

#### Explanation:

• The code above is a Java program that implements all logical operators with default values. The program defines a class LogicalOperators with a main method.
• In the main method, two boolean variables a and b are defined and assigned default values true and false, respectively.
• The program then prints the values of a and b to the console using the System.out.println method. This allows us to verify the values assigned to a and b.
• Next, the program calculates the result of the logical operators && (and), || (or), and ! (not) applied to a and b. The results of these operations are also printed to the console using the System.out.println method.
• The && operator returns true if both operands are true; otherwise, it returns false. In this case, the result of a && b is false.
• The || operator returns true if either operand is true; otherwise, it returns false. In this case, the result of a || b is true.
• The ! operator negates the value of its operand. If the operand is true, the result is false, and if the operand is false, the result is true. In this case, the results of !a and !b are false and true, respectively.
• The output of the program shows the truth table for all logical operators. This table provides a visual representation of how these operators behave for all possible combinations of true and false inputs.

### 5. Advantages of logical operators:

#### The advantages of using logical operators in a program include:

1. Readability: Logical operators make code more readable by providing a clear and concise way to express complex conditions. They are easily recognizable and make it easier for others to understand the code.
2. Flexibility: Logical operators can be combined in various ways to form complex conditions, making the code more flexible. This allows developers to write code that can handle different scenarios and respond dynamically to changes in the program’s inputs.
3. Reusability: By using logical operators, developers can write code that can be reused in different parts of the program. This reduces the amount of code that needs to be written and maintained, making the development process more efficient.
4. Debugging: Logical operators can help to simplify the debugging process. If a condition does not behave as expected, it is easier to trace the problem by examining the results of each logical operator rather than having to navigate through a complex code structure.

6. Disadvantages of logical operators :

1. Short-circuit evaluation: One of the main advantages of logical operators is that they support short-circuit evaluation. This means that if the value of an expression can be determined based on the left operand alone, the right operand is not evaluated at all. While this can be useful for optimizing code and preventing unnecessary computations, it can also lead to subtle bugs if the right operand has side effects that are expected to be executed.
2. Limited expressiveness: Logical operators have a limited expressive power compared to more complex logical constructs like if-else statements and switch-case statements. This can make it difficult to write complex conditionals that require more advanced logic, such as evaluating multiple conditions in a specific order.
3. Potential for confusion: In some cases, the use of logical operators can lead to confusion or ambiguity in the code. For example, consider the expression a or b and c. Depending on the intended order of operations, this expression can have different interpretations. To avoid this kind of confusion, it is often recommended to use parentheses to explicitly specify the order of evaluation.
4. Boolean coercion: Logical operators can sometimes lead to unexpected behavior when used with non-Boolean values. For example, when using the or operator, the expression a or b will evaluate to a if a is truthy, and b otherwise. This can lead to unexpected results if a or b are not actually Boolean values, but instead have a truthy or falsy interpretation that does not align with the programmer’s intentions.

#### Overall, logical operators are an important tool for developers and play a crucial role in the implementation of complex conditions in a program. They help to improve the readability, flexibility, reusability, and debuggability of the code.

My Personal Notes arrow_drop_up