Java - Comparison Operators
Java provides operators that can be used to compare values or values within variables. As the name implies.
The comparison operators include equal to and not equal to operators. Also known as equality operators.
Both comparison operators, equal to(==
) and not equal to(!=
) gives resultant value in boolean i.e either true
or false
after evaluation.
Equal to(==
) operator(double equal) checks, whether operands surrounding equal to operator are same or not. Whereas the single equal(=
) is used for assigning RHS(Right Hand Side) value or expression to LHS(Left Hand Side).
The not equal to(!=
) operator in Java checks, whether operands surrounding operator are different or not.
In this article, you will find Comparison operators Java supports.
Comparison operators
Basic comparisons performed on operands/variables with the use of equality operators.
Operator | Description | Example |
---|---|---|
== | Equal | a == b |
!= | Not Equal | a != b |
- Both of these operators
==
and!=
are binary operators. - These operators also follow the same general structure of
Operand
Operator
Operand
, meaning that an operator is always surrounded by two operands. - For example, an expression
a == b
is a binary operation, where a and b are the two operands and == is an operator. - If value of
a
&b
are same then you will getTrue
as value elseFalse
.
Example for different value in operands
int a = 12, b = 24;
System.out.println(a == b);
// Output: false
System.out.println(a != b);
// Output: true
Example for same value in operands
int a = 12, b = 12;
System.out.println(a == b);
// Output: true
System.out.println(a != b);
// Output: false
Generally these operators are use with if
statements.
Program to check whether the entered number is zero or non-zero
// ZeroNonZero.java
class ZeroNonZero
{
public static void main(String[] args)
{
int num = 55;
if (num == 0)
{
System.out.println('Zero');
}
else{
System.out.println('Non-zero');
}
}
}
More Java Programs
Hope you like this!
Keep helping and happy 😄 coding