Utilities.getDistance(uni, enemyuni) <= uni.getAttackRange()
Utilities.getDistance returns double and getAttackRange returns int. The above code is part of an if statement and it needs to be true. So is the comparison valid?
Thanks
Double compare() Method in Java with ExamplesThe compare() method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable. Suppose the value of ii is 3. Java creates a temporary value 3.0 that is the corresponding double value.
Yes, it's valid - it will promote the int
to a double
before performing the comparison.
See JLS section 15.20.1 (Numerical Comparison Operators) which links to JLS section 5.6.2 (Binary Numeric Promotion).
From the latter:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
...
When performing operations (including comparisons) with two different numerical types, Java will perform an implicit widening conversion. This means that when you compare a double
with an int
, the int
is converted to a double
so that Java can then compare the values as two double
s. So the short answer is yes, comparing an int and a double is valid, with a caveat.
The problem is that that you should not compare two floating-piont values for equality using ==
, <=
, or >=
operators because of possible errors in precision. Also, you need to be careful about the special values which a double can take: NaN
, POSITIVE_INFINITY
, and NEGATIVE_INFINITY
. I strongly suggest you do some research and learn about these problems when comparing double
s.
This should be fine. In floating point operation/comparisons, if one argument is floating/double then other one being int is also promoted to the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With