Home > Java > Operators > Logical Operators > Introduction
Introduction

Introduction to Logical Operators

The logical operators AND (&&), OR (||) and NOT (!) produce a boolean value of true or false based on the logical relationship of its arguments.


Syntax


// Result is true if both conditions are true.  For example, the result is true if operand1 is equal to operand2 and operand3 is equal to operand4 else false


operand1 ==  operand2 && operand3 == operand4


// Result is true if only one condition is true out of multiple conditions.  For example the result is true, if operand1 is equal to operand2 or operand3 is equal to operand4 else false


operand1 ==  operand2 || operand3 == operand4


// Converts true result into false and false into true. If operand1 is equal to operand2, result will be true but

NOT (!) will convert it into false and vice versa.


! (operand1 == operand2)


Example


1. /**
2. * @(#)LogicalOperatorsDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/3
7. */
8.
9.  public class LogicalOperatorsDemo {
10.        
11.    /**
12.     * Creates a new instance of RelationalOperatorsDemo.
13.     */
14.    public LogicalOperatorsDemo() {
15.    }
16.    
17.    /**
18.     * @param args the command line arguments
19.     */
20.    public static void main(String[] args) {
21.        // TODO code application logic here
22.        
23.      int a = 25;
24.      int b = 10;
25.        
26.      System.out.println("a is equal to 25 and b is equal to 10: " + (a==25 &&  b==10));
27.      System.out.println("a is equal to 25 or b is equal to 15: " + (a==25 ||  b==15));
28.      System.out.println("a is equal to 25 and b is not equal to 10: " + !(a==25 &&  b==15));
29.    }
30. }


In above example, both conditions are true on line 26 so result is true.  On line 27, first condition is true but second condition is false so result is true due to OR ( || ) operator. On line 28, first condition is true and second condition is false so result is false but
NOT ( ! ) operator converts it into true.

 

Output

 

a is equal to 25 and value of b is equal to 10: true
a is equal to 25 or value of b is equal to 15: true
a is equal to 25 and value of b is not equal to 10: true

Leave a Reply

Fields with * are mandatory.
* Name:
Website:
* Comments:
 
Tags allowed: <strong> <i> <u>
* Code:
 
 
Submit   Cancel