What is the difference between these lines?

Why toString() ?

Here I take the number from the array and compare with the reverse (I check for polindrom)

But if you remove toString() at the end of the condition, it will not work?

 for (int i = 0; i < n; i++) { if (Integer.toString(arr[i]).equals(new StringBuffer().append(Integer.toString(arr[i])).reverse().toString())) System.out.println(arr[i]); } 

But another example without toString() works:

 System.out.print(new StringBuffer().append("Hello").reverse()); 

elloH

  • 2
    Why toString ()? To get the string. But another example without toString () works: Because System.out.print does toString() for you. - PetSerAl 7:55 pm
  • 2
    equals accepts Object, and in the implementation itself there is such a construct if (anObject instanceof String) { ... } else return false; , since StringBuilder comes, that's why the condition is false. You can use contentEquals - Drawn Raccoon

1 answer 1

The System.out.print() method calls toString() automatically. So casting is not required. But the equals() method requires a parameter of the same type as the object itself. If you override this method, then the construction in the expression will work. For a more detailed understanding of how the print() method works, you need to look at the documentation.