Relational and logical operators

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

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:

1. Equal to (==)

Checks if two values are equal.

int a = 5;
int b = 5;
boolean result = (a == b); // true

2. Not Equal to (!=)

Checks if two values are not equal.

int a = 5;
int b = 3;
boolean result = (a != b); // true

3. Greater than (>)

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

4. Less than (<)

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

5. Greater than or Equal to (>=)

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

6. Less than or Equal to (<=)

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

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:

1. Logical AND (&&)

Returns true if both operands are true.

boolean a = true;
boolean b = false;
boolean result = (a && b); // false

2. Logical OR (||)

Returns true if at least one of the operands is true.

boolean a = true;
boolean b = false;
boolean result = (a || b); // true

3. Logical NOT (!)

Inverts the value of a boolean expression.

boolean a = true;
boolean result = !a; // false

Code Example

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
    }
}