Relational and logical operators are essential in Java for making decisions based on conditions. They are primarily used in control flow statements like if, while, and for loops to determine the flow of execution based on certain conditions.
Relational operators are used to compare two values. They return a boolean result (true or false) based on the comparison. Here are the relational operators in Java:
==)Checks if two values are equal.
int a = 5;
int b = 5;
boolean result = (a == b); // true
!=)Checks if two values are not equal.
int a = 5;
int b = 3;
boolean result = (a != b); // true
>)Checks if the value on the left is greater than the value on the right.
int a = 5;
int b = 3;
boolean result = (a > b); // true
<)Checks if the value on the left is less than the value on the right.
int a = 5;
int b = 8;
boolean result = (a < b); // true
>=)Checks if the value on the left is greater than or equal to the value on the right.
int a = 5;
int b = 5;
boolean result = (a >= b); // true
<=)Checks if the value on the left is less than or equal to the value on the right.
int a = 5;
int b = 8;
boolean result = (a <= b); // true
Logical operators are used to combine multiple boolean expressions or to invert the value of a boolean expression. Here are the logical operators in Java:
&&)Returns true if both operands are true.
boolean a = true;
boolean b = false;
boolean result = (a && b); // false
||)Returns true if at least one of the operands is true.
boolean a = true;
boolean b = false;
boolean result = (a || b); // true
!)Inverts the value of a boolean expression.
boolean a = true;
boolean result = !a; // false
Here is a complete Java program that demonstrates the use of relational and logical operators:
public class RelationalLogicalOperatorsDemo {
public static void main(String[] args) {
int x = 10;
int y = 20;
// Relational Operators
System.out.println("x == y: " + (x == y)); // false
System.out.println("x != y: " + (x != y)); // true
System.out.println("x > y: " + (x > y)); // false
System.out.println("x < y: " + (x < y)); // true
System.out.println("x >= y: " + (x >= y)); // false
System.out.println("x <= y: " + (x <= y)); // true
// Logical Operators
boolean a = true;
boolean b = false;
System.out.println("a && b: " + (a && b)); // false
System.out.println("a || b: " + (a || b)); // true
System.out.println("!a: " + (!a)); // false
// Combining Relational and Logical Operators
System.out.println("(x < y) && (a || b): " + ((x < y) && (a || b))); // true
}
}