5 Minutes of Java (6. Using equals() or ==)

Using == for comparision

In python, to compare whether two variables have the same value, we will write the following code:

if (a == b):

print “a is equal to b”

This works whether the data type of the variables is String or number.

In Java, you can still use == to compare whether two numbers have the same value:
int a = 3;
int b = 3;
if (a == b){

 System.out.println(“a and b has the same value”);

}

However, you should use the equals() method to compare String in Java. In the code segment shown below, if you enter “hello” for both inputs, only the following result will be displayed: “Using equals() for comparison: a is equal to b”.

String a = Helper.readString("Enter first String");
String b = Helper.readString("Enter second String");

if(a==b){
 System.out.println("Using == for comparison: a is equal to b");
}

if(a.equals(b)){
 System.out.println("Using equals() for comparison: a is equal to b");
}

In summary,

  • to compare numbers in Java, use ==
  • to compare Strings in Java, use equals()

Leave a Reply