Java Logical Operators

https‮/:‬/www.theitroad.com

Java logical operators are used to combine one or more boolean expressions and return a boolean value. The following are the logical operators in Java:

  1. Logical AND: &&
    The logical AND operator returns true if and only if both the left and the right operands are true.
boolean a = true;
boolean b = false;
boolean result = a && b; // result is false
  1. Logical OR: ||
    The logical OR operator returns true if at least one of the left or the right operands is true.
boolean a = true;
boolean b = false;
boolean result = a || b; // result is true
  1. Logical NOT: !
    The logical NOT operator returns the opposite boolean value of the operand.
boolean a = true;
boolean result = !a; // result is false

These operators can be used to form more complex boolean expressions. Here's an example that uses all three operators:

boolean a = true;
boolean b = false;
boolean c = true;
boolean result = (a && b) || (!c); // result is false

In this example, the expression (a && b) evaluates to false, and the expression (!c) evaluates to false. Therefore, the overall expression evaluates to false, which is assigned to the variable result.