Java Logical Operators

Logical operators are used to combine multiple conditions.
Let’s say you wanted your program to output “Welcome to HelloTech!” only when the variable num is greater than 20 and the variable salary is greater than 5000.
One way to accomplish this is to use nested if statements:

if (num > 20) {
 if (salary > 5000) {
 System.out.println("Welcome to HelloTech!");
 }
}

The AND (&&) Operator:

The AND operator (&&) checks if both operands of the AND operator are true, then the condition becomes true.The condition becomes false, if any one of the operands evaluates to false.
However,We can solve above problem using the AND logical operator (&&) in a better way:

if (num > 20 && salary > 5000) {
 System.out.println("Welcome to HelloTech!");
}

The OR (||) Operator:

The OR operator (||) checks if any one of the conditions is true. The condition becomes true, if any one of the operands evaluates to true.
For example:

int num = 25;
int salary = 1200;

if (num > 20 || money > 5000) {
 System.out.println("Welcome to HelloTech!");
}
//Outputs "Welcome to HelloTech!"

The code above will print “Welcome to HelloTech!” if num is greater than 20 or if salary is greater than 5000.

The NOT (!) Operator:

The NOT (!) logical operator is used to reverse the logical state of its operand. If a condition is true, the NOT logical operator will make it false.
Example:
int salary = 2500;
if(!(salary > 2000)) {
 System.out.println("Your salary is not greater than 2000");
} else {
 System.out.println("Welcome to HelloTech");
}
//Outputs "Welcome to HelloTech"

!(salary > 2000) reads as “if salary is NOT greater than 2000”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s