C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Compare Two Numbers using Relational Operators

Relational Operators Used

  • > Greater than
  • < Less than
  • == Equal to
  • != Not equal to
  • >= Greater than or equal to
  • <= Less than or equal to

 

import java.util.Scanner;

 

public class RelationalOperatorDemo {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter first number: ");

        int a = sc.nextInt();

 

        System.out.print("Enter second number: ");

        int b = sc.nextInt();

 

        System.out.println("\n--- Comparison Results ---");

 

        System.out.println("a > b  : " + (a > b));

        System.out.println("a < b  : " + (a < b));

        System.out.println("a == b : " + (a == b));

        System.out.println("a != b : " + (a != b));

        System.out.println("a >= b : " + (a >= b));

        System.out.println("a <= b : " + (a <= b));

 

        sc.close();

    }

}

Output

 

OUTPUT 1 :

INPUT :
Enter first number: 15
Enter second number: 10

OUTPUT :
--- Comparison Results ---
a > b  : true
a < b  : false
a == b : false
a != b : true
a >= b : true
a <= b : false
 
OUTPUT 2 :

INPUT :
Enter first number: 20
Enter second number: 20

OUTPUT :
--- Comparison Results ---
a > b  : false
a < b  : false
a == b : true
a != b : false
a >= b : true
a <= b : true
 

Explanation

1. What Are Relational Operators?

Relational operators compare two values and return a boolean result (true or false).

2. Operator Meaning Table

Operator

Description

Example

Greater than

a > b

Less than

a < b

==

Equal to

a == b

!=

Not equal to

a != b

>=

Greater than or equal

a >= b

<=

Less than or equal

a <= b