Java Equal to
In Java, Equal to Relational Operator is used to check if left operand is equal to second operand. In this tutorial, we will learn how to use the Equal to Operator in Java, with examples.
The symbols used for equal to operator is ==
. Equal to operator takes two operands: left operand and right operand as shown in the following.
left_operand == right_operand
The syntax to check if x
equals y
using Equal to Operator is
x == y
The operator returns a boolean value of true
if x
is equal to y
, or false
if not.
Examples
In the following example, we take two integer values in x
and y
, and check if these two are equal, using Equal to Operator.
Main.java
public class Main {
public static void main(String[] args) {
int x = 4;
int y = 4;
if (x == y) {
System.out.println("x and y are equal.");
} else {
System.out.println("x and y are not equal.");
}
}
}
Output
x and y are equal.
Since values in x
and y
are equal, x == y
returned true.
Now, let us take different values for x
and y
, and observe the result. Since, x
and y
are different, x == y
should returns false.
Main.java
public class Main {
public static void main(String[] args) {
int x = 4;
int y = 7;
if (x == y) {
System.out.println("x and y are equal.");
} else {
System.out.println("x and y are not equal.");
}
}
}
Output
x and y are not equal.
Since values in x
and y
are not equal, x == y
returned false.
Conclusion
In this Java Tutorial, we learned about Equal to Operator in Java, with examples.