The relational operators work well in conditions where only a single condition needs to be checked. Logical operators either return a True value or a False value based on the state of the Variables. The six logical or Boolean, operators used in the Java programming language are:
AND conditional AND OR conditional OR exclusive OR NOT
A logical operator accepts only arguments declared as Boolean data types. Also, these operators return value of Boolean data type.
These operators unlike the relational operators, that you already know, are used to check whether a set of conditions is true or not. In such as case, if statements are used. The code snippet below shows example of this:
if (num_var_1 == 4) { if (num_var_2 != 4) { System.out.println(“Both conditions are true.”); } }
However, as you can see this is not a user-friendly code, and is both harder to write and read. Such a code snippet becomes difficult to manage when multiple conditions are used. Let’s now look at the use of the following three conditional operators:&&, || and !.
The logical operator && combines two Boolean values and gives a True result if and only if both of its operands are true. This is shown in the following code snippet:
Boolean c; num_var_1 = 51 > 49 && 13 < 13; // num_var_1 is true num_var_1 = 44 > 52 && 7 < 9; // num_var_1 is now false
Similarly, the logical operator || combines two Boolean variables or expressions. It returns a true result only if either or both of its operands are true. Let’s look at the following code snippet which shows the rule:
Boolean d; num_var_4 = 51 > 49 || 73 < 91; // num_var_4 is true num_var_4 =
Continue reading JAVA – Logical /Boolean Operator