0

While coding I stumbled upon something like this (extremely simplified example):

public bool Func()
{
    Object[] array = new Object[] {false, false};
    return array[0] != array[1];
}

I was fooled thinking it would return false, but it instead returned true.

It did that because of C# comparing two Object references.

When I showed this to a friend he said, for him it always returns false. I wondered why, and soon I noticed he was using Java.

So in perspective of OOP I would think that true would be correct, but I can also understand why false is also acceptable.

Both languages are highly object oriented and I wonder why both are using different approaches in this case.

Shouldn't both languages have the same behaviour?

4
  • 1
    "Shouldn't both languages have the same behaviour?" The logical conclusion to that thinking is all languages should be the same single language. Clearly they are not
    – Caleth
    Commented Mar 6, 2019 at 15:23
  • Thats why i specified the case. While writing this question i stated it at the end again and deleted it because i though it was redundant Commented Mar 6, 2019 at 15:25
  • I was about to answer but deleted it again because i think this question really belongs to SO. I suspec Java is not as strict about the object equality rule and optimizes both array entries to the same object reference. Java also does that with strings in many cases.
    – marstato
    Commented Mar 6, 2019 at 15:32
  • Why should they be different instance? What different states might have a boolean value? Why should the jvm create new instances when the only two states possible are known up-front, are already loaded in memory and they are inmutable? In which cases true != true? Note that in Java wrappers are value objects not entities.
    – Laiv
    Commented Mar 7, 2019 at 21:14

1 Answer 1

3

When you put booleans (the primitive type) into an Object[]-array, Java will box them into Booleans (the reference type). I assume C# does the same. So it is indeed an object reference comparison.

However, the JLS specifies in section 5.1.7 on Boxing conversions:

If the value p being boxed is [...] true, false [...] then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

Thus, Java will use the same object reference for every time false is boxed (or at least references which compare as equal).

Why does Java do this and C# not? I think that is an off-topic question (and maybe this belongs on SO to begin with). Both seem to be reasonable decisions with their respective caveats.

Not the answer you're looking for? Browse other questions tagged or ask your own question.