Operators
Java Program to Demonstrate Relational Operators
A Java program to demonstrate the usage of relational operators.
Problem Description
Write a Java program to compare two numbers using relational operators.
Code
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
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));
}
}Output
a == b: false
a != b: true
a > b: false
a < b: true
a >= b: false
a <= b: trueExplanation
==(Equal to): Checks if values are equal.!=(Not equal to): Checks if values are not equal.>(Greater than): Checks if the left operand is greater than the right.<(Less than): Checks if the left operand is less than the right.>=(Greater than or equal to): Checks if the left operand is greater than or equal to the right.<=(Less than or equal to): Checks if the left operand is less than or equal to the right.
Try Yourself
- Compare Characters: Compare 'a' and 'b'. Is
'a' < 'b'true? Why? - Floating Point: Compare
10.0and10. Are they equal? - Negative Numbers: Is
-5 > -10true or false? - Equality Check: Be careful with
==vs=. Tryif (a = 10)and see the error. - Brain Twister: Why is
0.1 + 0.2 == 0.3false in Java? (Hint: Floating point precision).
