Dani Gilboa
Dani Gilboa

Reputation: 619

How are both of these variables the same?

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)?

Upvotes: 2

Views: 129

Answers (4)

Pankaj Shinde
Pankaj Shinde

Reputation: 3689

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.

Upvotes: 0

fge
fge

Reputation: 121712

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.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213223

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.

Upvotes: 7

djechlin
djechlin

Reputation: 60768

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 !=.

Upvotes: 1

Related Questions