0

Difference between == and equals in java?

27th Nov 2017, 3:15 PM
Mannu Joshi
Mannu Joshi - avatar
4 Answers
+ 12
== is a primitive equals operator. meaning, you can only compare primitive data types with it (int, float, string, ...) when working with objects such as objects of your own class or another objects (Integer, Double, ....) you can override the equals method to make comparison between objects why would one need such functionality you might ask? consider the following code Integer x1 = new Integer(5); Integer y1 = new Integer(5); int x2 = 5; int y2 = 5; so what would be the result of: System.out.println(x1 == y1); System.out.println(x2 == y2); answer would be *false* for the first print and *true* for the second one the reason behind this is that the == operator checks object *references* when comparing objects (non-primitives) therefore, the result would be different references for the newly instantiated Integer objects when comparing primitives, the values are checked and if you were to do: System.out.println(x1.equals(y1)); the equals operator would compare the values inside the objects to return the value *true*. a much briefer explanation in here 😅 https://www.sololearn.com/discuss/270604/?ref=app
27th Nov 2017, 6:35 PM
Burey
Burey - avatar
+ 1
The operator == is to compare only primitive data types. Strings are reference types: - reference on the Stack - value on the Heap For String comparison use the 'equals()' method. If you compare Strings with the == operator, you compare their references, not their values. Assume this: String a = "string"; String b = "string"; System.out.println(a == b); // true Looks like it works, but that's because the JVM checks, whether the String b value already exists in the String pool, and if it's found, the String b will get the same reference as the String a. That's, to save memory. But here, the == operator will fail: String a = "string"; String b = new String("string"); System.out.println(a == b); // false That's simply, because we allocate new different address on the Heap for that value, so the reference on the Stack of String b now will be different from String a.
28th Nov 2017, 1:17 AM
Boris Batinkov
Boris Batinkov - avatar
0
== to test equality of condition = is the assignment operator
27th Nov 2017, 3:39 PM
Andika Romansyah
0
== returns a boolean value of either true or false = assigns a value to a variable. equals() also functions as ==
27th Nov 2017, 4:03 PM
᠌᠌Code X
᠌᠌Code X - avatar