Java Relational Operators and Examples

Relational operators are operators that allow us to control relationships between two operands (such as equality, inequality, greater than or less than) and enable us to create logical statements with conditional expressions by returning boolean results.

Java Relational Operators and Examples

Java Equals To Opetator: ==

The equality operator checks if the operands to the left and right of the equation are equal and returns one of the true or false boolean results.

Examples for various data types

boolean a = 5==5;
System.out.println(a); //true

int someInteger=6;
boolean b = someInteger-1 == 5;
System.out.println(b); //true

boolean c = a==b;
System.out.println(c); //true

boolean d= "Hello" == "hello";
System.out.println(d); //false

boolean e= "hello" == "hello";
System.out.println(e); //true

 

Java "Not Equals" Opetator: !=

‘Not equal to’ (!=) operator returns true if the operands at the both sides are not equal

Examples for various data types

boolean a = 6 != 6;
System.out.println(a); //false because 6=6

int someInteger=11;
boolean b = someInteger-5 != 6;
System.out.println(b); //false

boolean c = a!=b;
System.out.println(c); //false because a=false and b=false

boolean d= "Hi" != "hi";
System.out.println(d); //true

boolean e= "whats up" != "whats up";
System.out.println(e); //false

 

"Less Than" (<) And "Greater Than" (>) Operators

This operators check whether the first operand is less/greater than the second operand or not. They both return false in case of equality

Examples for int and double data types

boolean a = 5 > 3;
System.out.println(a); //true

int someInteger=20;
boolean b = someInteger-10 > 10;
System.out.println(b); //false

boolean c = 5 < 5;
System.out.println(c); //false

boolean d= 20.1 > 20;
System.out.println(d); //true

double someDouble = 1.001;
boolean e= someDouble < 1.0005;
System.out.println(e); //false

 

"Less Than or Equal To" (<=) And "Greater Than or Equal To" (>) Operators

This operators check whether the first operand is less/greater than or equals to the second operand or not. They both return true in case of equality.

Examples for int and double data types

boolean a = 5 >= 5;
System.out.println(a); //true

int someInteger=35;
boolean b = someInteger-10 <= 25;
System.out.println(b); //true

boolean c = 5 <= 5;
System.out.println(c); //true

boolean d= 20.1 >= 20;
System.out.println(d); //true

double someDouble = 1.001 - 0.0005;
boolean e= someDouble <= 1.0005;
System.out.println(e); //true