0
0
Javaprogramming~5 mins

Relational operators in Java

Choose your learning style9 modes available
Introduction

Relational operators help us compare two values to see how they relate to each other, like if one is bigger or smaller.

Checking if a student's score is above the passing mark.
Deciding if a person is old enough to vote.
Comparing prices to find the cheaper product.
Determining if a number is equal to another number.
Finding out if a temperature is below freezing.
Syntax
Java
value1 < value2
value1 <= value2
value1 > value2
value1 >= value2
value1 == value2
value1 != value2

Use == to check if two values are equal.

Use != to check if two values are not equal.

Examples
This checks if a is less than b. The result will be true.
Java
int a = 5;
int b = 10;
boolean result = a < b;
This checks if age is at least 18 to allow voting.
Java
int age = 18;
boolean canVote = age >= 18;
This checks if x and y are equal.
Java
int x = 7;
int y = 7;
boolean equal = x == y;
This checks if temp is not zero (not freezing).
Java
int temp = 30;
boolean notFreezing = temp != 0;
Sample Program

This program compares the student's score with the passing score using relational operators and prints the results.

Java
public class RelationalOperatorsDemo {
    public static void main(String[] args) {
        int score = 75;
        int passingScore = 60;

        System.out.println("Score: " + score);
        System.out.println("Passing Score: " + passingScore);

        System.out.println("Did the student pass? " + (score >= passingScore));
        System.out.println("Is the score less than 50? " + (score < 50));
        System.out.println("Is the score equal to 75? " + (score == 75));
        System.out.println("Is the score not equal to 100? " + (score != 100));
    }
}
OutputSuccess
Important Notes

Relational operators always return a boolean value: true or false.

Use parentheses to make complex comparisons clear.

Summary

Relational operators compare two values and return true or false.

They include <, <=, >, >=, ==, and !=.

They are useful for making decisions in programs.