Logical Operators in Java

ZoneTechPro
By -
0


Logical Operators in Java



Java - Logical Operators



Introduction

Logical operators in Java are used to perform logical operations on boolean values. They help in decision-making expressions and are often combined with relational operators. The result of a logical operation is always true or false.


Logical Operators in Java


Java provides three primary logical operators:




Logical AND (&&) Operator :

  • The AND (&&) operator returns true only if both conditions are true.
  • If the first condition is false, the second condition is not evaluated.



Truth Table for AND (&&):



Truth Table - AND
Java - Truth Table - AND



Example 1: AND Operator:



class Main {

    public static void main(String[] args) {

        System.out.println((2 < 3) && (1 < 2));  // true

    }

}


Explanation:

  • (2 < 3) && (1 < 2)
  • true && truetrue

Example 2: AND Operator with a False Condition :


class Main {

    public static void main(String[] args) {

        System.out.println((10 < 5) && (6 < 9));   // false

    }

}




Explanation:

  • (10 < 5) && (6 < 9)
  • false && (6 < 9)
  • Since the first condition is false, Java does not check the second condition.



Logical OR (||) Operator :

  • The OR (||) operator returns true if at least one condition is true.
  • If the first condition is true, the second condition is not checked.



Java - OR operator
Java - OR operator




Example 1: OR Operator:



class Main {

    public static void main(String[] args) {

        System.out.println((12 > 13) || (15 < 12));  // false

    }

}



Explanation:


  • (12 > 13) || (15 < 12)
  • false || falsefalse


Example 2: OR Operator with a True Condition :

class Main {

    public static void main(String[] args) {

        System.out.println((2 < 3) || (2 < 1));  // true

    }

}



Explanation:


(2 < 3) || (2 < 1)
true || (2 < 1)
Since the first condition is true, Java does not check the second condition.


Logical NOT (!) Operator:


  • The NOT (!) operator is a unary operator that inverts the boolean value.
  • If a condition is true, applying ! makes it false, and vice versa.


Logical NOT Operator
java - Logical NOT Operator



Example 1: NOT Operator:



class Main {

    public static void main(String[] args) {

        System.out.println(!(5 > 7));  // true

    }

}


Explanation:

  • !(5 > 7)!(false)true


Example 2: NOT Operator with a True Condition :

class Main {

    public static void main(String[] args) {

        System.out.println(!(2 < 3));  // false

    }

}


Explanation:

  • !(2 < 3)!(true)false


Summary

  • Logical AND (&&) returns true only if both conditions are true.
  • Logical OR (||) returns true if at least one condition is true.
  • Logical NOT (!) reverses the boolean value.



Tags:

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!