Comparing Numbers in Java

A Double is NEVER equals to an Integer. Moreover, a double is not the same as a Double.

Java has primitive types and reference types. The truly numeric types in Java do not extend from Number, because they’re primitives.

You may want to consider a system where you’re not mixing types, because that usually will cause a lot of trouble with implicit/explicit conversions that may/may not lose information, etc.

Related questions

On int vs Integer:

On Number comparison:

See also


On mixed-type computation

Mixed-type computation is the subject of at least 4 puzzles in Java Puzzlers.

Here are various excerpts:

it is generally best to avoid mixed-type computations […] because they are inherently confusing […] Nowhere is this more apparent than in conditional expressions. Mixed-type comparisons are always confusing because the system is forced to promote one operand to match the type of the other. The conversion is invisible and may not yield the results that you expect

Prescription: Avoid computations that mix integral and floating-point types. Prefer integral arithmetic to floating-point.

Leave a Comment