简体   繁体   中英

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 Integer s 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.

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.

2, 4 and 5 are true .

Although remember that comparing floats by == might be tricky, it's safer to do this like this:

Math.abs(float1 - float2) < epsilon

where epsilon is some small number (precision).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM