Is it valid to compare a double with an int in java?

后端 未结 6 1381
暗喜
暗喜 2020-11-28 10:41
Utilities.getDistance(uni, enemyuni) <= uni.getAttackRange()

Utilities.getDistance returns double and getAttackRange returns int. The above code

相关标签:
6条回答
  • 2020-11-28 10:50

    It will be ok.

    Java will simply return true of the numerical value is equal:

        int n = 10;
        double f = 10.0;
        System.out.println(f==n);
    

    The code above prints true.

    0 讨论(0)
  • 2020-11-28 10:51

    yes it is absolutely valid compare int datatype and double datatype..

    int i =10;
    double j= 10.0;
     if (i==j)
    {
    System.out.println("IT IS TRUE");
    }
    
    0 讨论(0)
  • Yes it valid, and your code should work as expected without any glitch, but this is not the best practice, static code analyzers like SonarQube shows this as a "Major" "Bug",

    Major Bug img from sonarQube

    Major Bug description from sonarQube

    so, the right way to do this can be,

    Double.compare(val1,val2)==0 
    

    if any parameter are not floating point variable, they will be promoted to floating point.

    0 讨论(0)
  • 2020-11-28 11:03

    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 doubles. 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 doubles.

    0 讨论(0)
  • 2020-11-28 11:05

    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.

    • ...

    0 讨论(0)
  • 2020-11-28 11:13

    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.

    0 讨论(0)
提交回复
热议问题