Read Java Interview Questions and Answers for Beginners and Experienced

Java equals to operator example

In this Java examples series of Java tutorial, we will see Java equals to operator example.

 


Equals to Operator in Java

As its name suggest “Equals to” means to check whether both variables are equals or not. In Java comparison operators , Java Equals to operator is kind of operator which used to compare two variables equality.

Equal to operator is written as == in Java.  Result of Equals to operator is either true or false. If both variables are same then result is true, otherwise result is false.

 


Syntax of Equals to Operator in Java

Syntax of == operator in java is

X ==Y;

  • X and Y are two variables.
  • == is the Equals to operator.

 


Java equals to operator example

We read about == operator in Java and also we see the syntax of it, Now let’s understand equals to operator in Java with example.

public class JavaExamples {

public static void main(String[] args) {
//Java equals to Operator Example in Java
int a=10;
int b=20;
int c=30;
int d=10;

System.out.println(a==b);
System.out.println(b==c);
System.out.println(c==d);
System.out.println(a==d);

}

}

Output

false
false
false
true

 

Explanation

In the above Java comparison equals to operator example, there are four variables a,b,c and d. only a and d has same values. rest are different values, so when we applied equals to operator on a and d, It returns true and for other comparisons it returns false.

 


Compare two Strings with Equals operators

In Java, two Strings can be compared with  equals to operator. Let’s understand this with taking an example.

public class JavaExamples {

public static void main(String[] args) {
//Java greater than equal to Operator with Strings Example in Java
String name1="ByteArray.in";
String name2="ByteArray.in";

System.out.println("both Strings are equals :"+(name1==name2));



}

}

Output

both Strings are equals :true


 

Explanation

In the program , there are two Strings name1 and name2. both have same values. by using == operator we can compare two Strings. in above example, it is returning true because both strings contains same values.

 


 

== is called equals to operator in Java and used to compare two values whether they are equals or not. It returns true if both are same otherwise it returns false.