Search code examples
javacomparisoncomparison-operators

Comparison with operator ==, how does it work?


I came up with the following question in a Java test:

import java.awt.Button;
class CompareReference 
{
    public static void main(String [] args) 
    {
        float f = 42.0f;
        float [] f1 = new float[2];
        float [] f2 = new float[2];
        float [] f3 = f1;
        long x = 42;
        f1[0] = 42.0f;
    }
}

which three statements are true?

  1. f1 == f2
  2. f1 == f3
  3. f2 == f1[1]
  4. x == f1[0]
  5. f == f1[0]

I need to choose only 3 statements.

Well, 1 is obviously false because we'were comparing two different references, 2 is obviously true because the references are the same. But I don't know about primitives. What I'm confused by is that if we compare Integers in range -128 to 127 they are caching. Related topic. Is there something about primitives, some narrow cases?

I was looking for how it works in the JLS 8 but didn't find anything useful.


Solution

  • Comparison 3 will not compile: it tries to compare an array to a scalar.

    Comparisons 4 and 5 involve primitives and are done by value. There are no references or autoboxing involved. Therefore the following is not relevant here:

    What I'm confused by is that if we compare Integers in range -128 to 127 they are caching.

    Since 42 can be represented exactly as a float, comparison 4 will return true.

    Comparison 5 will also return true since it's comparing two identical float values.