- These operators are used to compare two values for equality or comparison.
- Result of each comparision is boolean (true or false)
Operator Description
== Equal to Returns true if compared values are equal
!= Not Equal to Returns true if compared values are not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
boolean flag = 10 > 5 ; // flag set to true
- These are mostly used with if block , different kind of loops (for,while,do while)
to alter the program flow based on boolean output
int num1 = 10 ;
int num2 = 20 ;
if (num1 == num2)
{
// do something
}
Remember, == operator is for equality check whereas = operator is assignment operator - Only Numeric types (int,float) and character type can be compared with relational operators
- == and != can be used for any type
Use of == operator with String type and Objects
When you compare primitive types (int,float) using ==
you will get desired result but with Strings and other
Objects, you will get surprising results.
Case 1
String str1 = new String ("abc") ;
String str2 = new String ("abc") ;
if (str1 == str2)
{
// statement1
}
else
{
// statement2
}
Which statement would get executed ?
Apparently statement1 but actually statement2 would get executed
== compares the memory address for Objects (Strings are objects in Java)
As str1 and str2 have different memory addresses, comparison evaluates to
false and else block is executed.
Case 2
String str1 = "abc" ;
String str2 = "abc" ;
if (str1 == str2)
{
// statement1
}
else
{
// statement2
}
Now which statement would be executed ?
This time statement1
When Strings are initialized as literals , same value Strings
will have only one copy.Hence str1 and str2 point to same
location in memory