Gentlemen, I apologize for maybe a stupid question, and even ask it - what happens if you add a double and an int?

Thank you in advance)))

  • 2
    I'm sorry, but what's stopping you from checking it out yourself? - DreamChild
  • Good answer))) Just have the code double a = 1.56; int c = 5; int d = 3; b = (int) (a + c + d); came 0 if you remove the type cast, then nothing comes at all - alexmx
  • I understand that for me it will be the output b = ((int) (a)) + c + d; - alexmx
  • What is b with you? - DreamChild
  • int b = 0; - alexmx

3 answers 3

when adding int and double, the result is double, because double has a larger range than int. In your case, you put the result (which, once again, is of type double) in an integer variable. Of course, int cannot store floating point numbers, so a rounded number will be stored in b. and the number will be 9, not 0, as you indicated. Example

    Here is a crib that where and how you can bring (took Horstmann):

    - solid line - lossless conversion.

    - dash - when casting losses are possible.

    in other cases, an explicit cast (in parentheses) is required.

    alt text

      When added, it will be double. If I remember correctly, in arithmetic operations, if at least one operand is of the double type, the other operands are given in double and as a result the double is output. Correct me if I'm wrong.

      • It looks like something is wrong, since removing the cast to an int didn’t come at all - alexmx
      • You have b - a variable of type int. Try to explicitly specify a calculated expression when outputting through System.out.println (). If there is a point in the output number, it is double. And you will see that the result is double. And in int it is rounded. - Yuri_Prime