Logical Operators in java 7

Ads
 

Logical Operators in java 7

In this tutorial, we are going to discuss about logical operator in java 7.

In this tutorial, we are going to discuss about logical operator in java 7.

Logical Operators in java 7

In this tutorial, we are going to discuss about logical operator in java 7.

Logical Operator :

Logical operators are used to check some logical conditions. These are of boolean type as they return true/false value.

Suppose X and Y are two operands and its value is true and false respectively.

&& (Logical AND Operator) This is logical operator and returns true if both operands are true otherwise false.

Example : X && Y -This expression will return false.

|| (Logical OR Operator) This logical operator returns true if any one of the given operands is true and returns false if all the operands are false.

Example : X || Y - This expression will return true.

! (Logical NOT Operator) This operator is used to invert the logical state of its operand. For example if operand value is true then this operator reverse its value that is false.

Example : !(X&&Y) - This expression will return true.

These logical operators is very useful where you want to check more than one conditions.

Example :

package operator;

class LogicalOperator {
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		int z = 100;
		boolean test;
		System.out.println("X = " + x);
		System.out.println("Y = " + y);
		System.out.println("Z = " + z);

		test = (x < y) && (y < z);
		System.out.println("(X < Y) && (Y < Z) : " + test);

		test = (x < y) || (x < z);
		System.out.println("(X < Y) || (X < Z) : " + test);

		test = !(x < z);
		System.out.println("!(X < Z) : " + test);
	}
}

Output :

X = 10
Y = 20
Z = 100
(X < Y) && (Y < Z) : true
(X < Y) || (X < Z) : true
!(X < Z) : false

Ads

Ads