Relational and Equality Operators Tutorial

The equality and relational operators are used to compare two operands and return a true/false value. This tutorial will provide a simple example of how the relational operators function. The Java relational operators are as follows:
== equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
!= not equal to



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md Relational
C:\Java>cd Relational
C:\Java\Relational>Notepad Relational.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class Relational {
    public static void main(String args[]) {
        //declaration statements can string together comma-separated variables as long as the data type is the same.
        int a=5, b=6; // don't confuse the assignment operator equals = with the relational operator == equal to.

        System.out.println(a == b); // equal to relational operator
        System.out.println(a > b); // greater than relational operator
        System.out.println(a >= b); // greater than or equal to relational operator
        System.out.println(a < b); // less than relational operator
        System.out.println(a <= b); // less than or equal to relational operator
        System.out.println(a != b); // not equal to relational operator
       
    }
}

Now switch back to the command prompt (CMD) and type in javac Relational.java and press Enter.
Now type in java Relational and press Enter.


C:\Java\Relational>javac Relational.java
C:\Java\Relational>java Relational
false
false
false
true
true
true


Final thoughts

As you can see, the relational operators simply return either a true or false value based on a conditional expression. Conditional expressions are used throughout many control statements in the Java language. Understanding how they work is critical to being a successful programmer.


Tutorials