Why this output is coming different | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why this output is coming different

Integer comparison https://code.sololearn.com/cSmmLzLm6XwL/?ref=app

20th Mar 2019, 3:44 PM
Dinesh Dilip Waditke
Dinesh Dilip Waditke - avatar
7 Answers
+ 7
Do this: System.out.println(i2.equals(i3)); // true Instead of: System.out.println(i2==i3); //false
20th Mar 2019, 4:11 PM
VEDANG
VEDANG - avatar
+ 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.
20th Mar 2019, 5:42 PM
Tibor Santa
Tibor Santa - avatar
20th Mar 2019, 3:56 PM
Sarthak Pokhrel
Sarthak Pokhrel - avatar
0
.equals is fine but what about ==
20th Mar 2019, 4:12 PM
Dinesh Dilip Waditke
Dinesh Dilip Waditke - avatar
0
S Pace 👍👍
20th Mar 2019, 4:24 PM
Dinesh Dilip Waditke
Dinesh Dilip Waditke - avatar