The logical operators are normally used to create a compound boolean expression.
In java they inlcude:
!
– ‘logical not operator’&&
– ‘logical and operator’||
– ‘logical or operator’^
– ‘exclusive logical or operator’
Logical operators are important when you want to execute a statement based on one or several coditions.
Logical operators can combine multiple conditions to for a compound boolean expression.
Logical operators are also known as boolean operators. They operate on boolean values yet still create a boolean value as a result.
Operator | Name | Description |
---|---|---|
|| |
or | logical disjunction |
&& |
and | logical conjunction |
! |
not | logical negation |
^ |
exclusive or | logical exclusion |
Example
import java.util.Scanner;
/**
* MrLogical
*/
public class MrLogical {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter Your Age: ");
int age = input.nextInt();
System.out.print("Enter Your Gender: ");
String gender=input.next();
if (age < 5 && gender.equalsIgnoreCase("male"))
{
System.out.println("You are baby boy");
}
if (age < 5 || gender.equalsIgnoreCase("male"))
{
System.out.println("You are a baby or a boy");
}
if (age < 5 ^ gender.equalsIgnoreCase("male"))
{
System.out.println("You are either a baby or a boy but not both.");
}
if (!gender.equalsIgnoreCase("male"))
{
System.out.println("You a female");
}
}
}
Result
Enter Your Age: 4
Enter Your Gender: female
You are a baby or a boy
You are either a baby or a boy but not both.
You a female