Logical operators are used to combine one or more relational expressions that results in formation of complex expressions known as logical expressions. Like relational operators, the logical operators evaluate the result of logical expression in terms of Boolean values that can only be true or false according to the result of the logical expression.
In Java, there are six logical operators: logical AND (&), logical OR (|), logical exclusive
OR i.e. XOR (^), logical negation (!), conditional AND (&&), conditional OR (||). All the logical operators are binary operators except logical negation which is a unary operator. The logical AND (&) operator evaluates to true if and only if both its operands evaluates to true. The logical OR (I) operator evaluates to true if and only if either of its operands evaluate true. The logical exclusive OR i.e. XOR (^) operator evaluates to true if and only if either, but not both, of its operands are true. In other words, it evaluates to false if both the operands are false.
The logical NOT(!) operator takes a single operand and evaluates to true if the operand is false and evaluates to false if the operand is true.
Table shows you the different Logical Operators used in Java Programming
Logical Operators
Operators | Meaning |
&& || ! | Logical AND Logical OR Logical NOT |
The logical operators && and || are used when we want to form compound conditions by combining two or more relations. Logical operators return results indicated in the following table.
x | Y | X && Y | X || Y |
T T F F | T F T T | T F F F | T T T F |
//program Showing Logical Operations
public class LogicalOperators
{
public static void main (String [] args)
{
int x=6 ,y=4,z=5;
System.out.println(" x>y & y>z-->" + (x>y & y>z));
System.out.println(" x>y | y>z-->" + (x>y | y>z));
System.out.println(" x>y ^ y>z-->" +(x>y ^ y>z));
System.out.println(" x>y && y>z-->" + (x>y&& y>z));
System.out.println(" x>y || y>z-->" + (x>y||y>z));
System.out.println(" !(x>y)--> " + (!(x>y)));
}
}
Java Example to implement Logical Operators using Scanner Class.
import java.util.*;
import java.lang.*;
class LogicalOperatorsUsingScanner
{
public static void main(String args[])
{
int x,y,z;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Value of x : ");
x=scan.nextInt();
System.out.print("Enter the Value of y : ");
y=scan.nextInt();
System.out.print("Enter the Value of z : ");
z=scan.nextInt();
System.out.println("x>y and x>z : "+((x>y) &&(x>z)));
System.out.println("x not equal to z : "+(x!=z));
}
}