Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing String and Integer with equals

The output of the below code is false

String str = "3456";
String str1 = "3456";
System.out.println(Integer.valueOf(str).equals(str1));

I didn't understand it. I thought it will return true. As I am preparing for SCJP, understanding the reason behind it may be helpful. Can someone please help?

like image 483
Anand Avatar asked Dec 02 '22 18:12

Anand


1 Answers

An Integer will never be equal to a String.

Both classes have very strict equals() definitions that only accept objects of their respective types.

  • Integer.equals():

    The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

  • String.equals():

    The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

That's actually a quite common way to implement equals(): only objects of the same class (and occasionally subclasses) can be equal. Other implementations are possible, but are the exception.

One common exception are the collections such as List: every List implementation that follows the convention will return true when compared to any other implementation, if it has the same content in the same order.

like image 90
Joachim Sauer Avatar answered Dec 16 '22 01:12

Joachim Sauer