Logical operators in java
There are many types of operators in java :
- Arithmetic operator
- Unary operator
- Relational operator
- Logical operator
- Assignment operator
- Ternary operator
- Bitwise operator
Logical operator :
Logical operators are used to perform logical AND , logical OR and logical NOT operations on the operands . It is used to check whether the expression or condition is true or false.
logical AND operator :
If there is two conditions given , if both conditions are true then only overall condition is true . Among the two if any one , or both the condition is false, then overall condition will be false . It is denoted by && . Syntax : condition1 && condition2 , if both condition are true then only overall condition is true.
example1:
int a=20 ,b=10,c=3;
if (a>b && a>c)
{
System.out.println("a is greater");
}
else
{
System.out.println("condition false");
}
OUTPUT : a is greater , because 20 is greater than 10 as well as 3.
example 2:
int a=20 ,b=10,c=33;
if (a>b && a>c)
{
System.out.println("a is greater");
}
else
{
System.out.println("condition false");
}
OUTPUT : condition false ,because 20 is greater than 10 but smaller than 33.
Logical OR :
Among the two condition if anyone condition or both conditions are true then overall condition is true. If both condition are false then overall condition is false.
It is denoted by | |. Syntax: condition1 || condition2.
example1:
int a =38 ,b=18 ,c=3;
if(a>b| |a<c )
{
System.out.println("condition is true: one condition is true");
}
else
{
System.out.println("condition false");
}
OUTPUT: condition is true , because both condition are true .
example2:
int a =38 ,b=18 ,c=3;
if(a>b| |a>c )
{
System.out.println("condition is true:both conditions are true");
}
else
{
System.out.println("condition false");
}
OUTPUT: condition is true ,because if any one condition is true means overall condition is true.
OUTPUT:Logical NOT ( ! ):
It is not like AND and OR operator .In this if the condition is true it gives false . if condition is false it gives true . It is denoted as ! . Syntax : ! (condition ) , Only one condition is required.
example :
int a=5,b=4;
System.out.print (!(a>b)); //!(true ) : output will be false .
System.out.println(!(a<b)); //! (false) : output will be true.