+ 3
Why this output is coming different
Integer comparison https://code.sololearn.com/cSmmLzLm6XwL/?ref=app
7 Réponses
+ 7
Do this:
System.out.println(i2.equals(i3));
// true
Instead of:
System.out.println(i2==i3);
//false
+ 4
== works only with primitive types such as int and char.
When you compare objects, such as Integer or String, you must use the equals() method of the object for comparison. This is always implemented in a way that compares the *contents* or *value* of the objects (no matter how complicated the objects are). The == operator only compares the *reference* of objects. The java compiler may reuse the same memory spot for multiple Objects, if you create them with the same value... MAY. But this is really not up to the user or programmer to control. Thats why your code produces true / false in a seemingly random manner.
+ 3
But this gives same result
https://code.sololearn.com/cp7bwdvFJt8K/?ref=app
0
.equals is fine but what about ==
0
S Pace 👍👍