Relational and Logical Operator

Author: Ravi Poswal

Relational Operator

Java's relational operators are used to compare two expressions or values. They give back either true or false as a boolean response. this operator is used in decision-making (i.e., if, while, for). 

Example:

Operator Meaning Example Result
== Equal to a == b true if equal
!= Not equal to a != b true if not equal
> Greater than a > b true if a is greater
< Less than a < b true if a is smaller
>= Greater than or equal to a >= b true if a ≥ b
<= Less than or equal to a <= b true if a ≤ b

 

Logical Operator

Java logical operators can be used to perform logical operations on boolean values. These operators are commonly used in decision-making statements such as if conditions and loops that control program flow.

Operator Name Description Example
  &&  AND If both conditions are true, then it returns true (x > y && x > 0)
     ||  OR

Depend on truth table

    a    b Result (a || b)
    T    T     T
    T    F     T
    F    T     T
    F    F     F
(x > y || x > 0)
  ! Logical NOT Reverses the result (true becomes false) !(a > b)

 

Code Example

import java.util.*;
public class RelationalEx {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        int y=sc.nextInt();
        System.out.println(x == y);  // false
        System.out.println(x != y);  // true
        System.out.println(x > y);   // true
        System.out.println(x < y);   // false
        System.out.println(x >= y);  // true
        System.out.println(x <= y);  // false

System.out.println(x > y && x > 0);
System.out.println(x > y || x > 5); 
System.out.println(!(x > 5));   
    }
}

FAQs

.

== (Equal to)
!= (Not equal)
< (Less than)
> (Greter than)
<= (Less than equal)
>= (Greter than equal)

.

&& (Logical AND)
|| (Logical OR)
! (Logical NOT)

Relational operators compare two values and return a boolean result. Logical operators combine multiple boolean conditions and return a final boolean value. Relational operators are used for comparison, while logical operators are used for combining conditions.