简体   繁体   中英

java: double == and Double equals

I am confused on a few things regarding using double.

  1. If i were to initialize 2 doubles with the same literal, would == always evaluate to true? for example, if following outputs true but i don't know if this is by chance:

     double a = .1d; double b = .1d; System.out.println(a==b); 
  2. I get the same result when using Double instead of double:

     Double a = .1d; Double b = .1d; System.out.println(a.equals(b)); 

According to Double documentation, equals() return true if doubleValue() are equal.

So the question is, is "==" for double and "equals()" for Double guaranteed to evaluate to true for 2 variables initialized using the same literal?

When would they evaluate to false? Is this when arithmetic operations are involved?

Thanks

In general == is an operator which checks for equality. Object variables are references so it checks for reference or address equality. In the case of primitive data types representing values in the memory that also means that it checks for value equality.

The method equals(~) checks for value or content equality. You do not use it for primitive data types but for Objects.

That is also the case for double and Double. The problem which is arising with doubles is the mismatch of the values induced by rounding errors.

Some arithmetic operations may handle rounding differently so you might get false for value equality even if you think it should be equal.

It should be stated that even if the rounding rules are a bit inconsistent arithmetic operations are deterministic so that inconsistency can be handled.

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