Question

Why is it that these two integers

Long num = new Long(21); 
long num2 = 21;

return true when compared (num==num2)

But this string

String word1 = "Hello";
String word2 = new String("Hello");

return false when compared (word1==word2)?

Was it helpful?

Solution

In the first case, you compare a Long reference with the long primitive type, in which case the Long reference undergo automatic unboxing conversion, and the comparison is done between two primitive longs, and hence they are equal. This is in accordance with JLS §5.6.2 - Binary Numeric Promotion.

While in second case, you are comparing two different references, both pointing to two different objects, and hence they have different value, and return false.

OTHER TIPS

In your former example num is cast to a long and the comparison succeeds.

In your second case the two different objects have different addresses and are therefore !=.

Because in the case of numeric equality, the JVM performs autounboxing (ie it turns the Long into a long) since one argument of == is a long.

In the second case, "Hello" and new String("Hello") are two different objects. And in the case of objects, == is true only if references are the same.

In first case

num is downcasted to long and compared by value 21, so it returns true.

In second case

new operator in java always creates new object, so word2 points to new object, so word1==word2 returns false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top