0

I am very confused on how the output gives me 7.5. I understand the part where it outputs a double but no clue why 7.5. I tried doing it myself following the rules to my knowledge and I got 6. If anyone could help me with understanding what java does to get the answer 7.5

public class pc1 {

    public static void main(String[] args) {

        System.out.println((double) (10 / 4) * (int) 10.0 / 4 + (double) 10 / 4);

    }

}
maloomeister
  • 2,461
  • 1
  • 12
  • 21
yukoi
  • 13
  • 1
  • 1
    What result are you expecting, and specifically why? If you break apart these operations into individual lines of code, what do you come up with and what result do you get? – David Sep 20 '21 at 13:35
  • 1
    Does this answer your question? [What is the priority of casting in java?](https://stackoverflow.com/questions/23464036/what-is-the-priority-of-casting-in-java) – ATP Sep 20 '21 at 13:38
  • let take this step by step (double) (10 / 4) 10/4 will be divided as integer which will give 2 then cast this 2 to be double so it be like 2.0 then int (10.0) will convert 10 to int 10 then it will mulitplay it with 2 from the previous calculations which give 20 as double then devide that by 4 which give 5.0 as double also then then cast 10 as double and dvide it by 4 whic give 2.5 then add this to the previous 5.0 which give 7.5 check the precednce order https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html –  Sep 20 '21 at 13:39

2 Answers2

2

Here is how you group them and the explanation.

System.out.println((double) (10 / 4) * (int) 10.0 / 4 + (double) 10 / 4);

prints

7.5
  • multiplication and division are computed left to right before addition and subtraction

(double) (10/4) * 10 /4;

  • so first 10/4 = 2 (integer math) then it is cast to 2.0
  • then that is multiplied by 10 to get 20.0
  • then 20.0 is divided by 4 to get 5.0

(double) 10 /4);

  • 10 is cast to double getting 10.0 so 10.0/4 = 2.5

Now add both results (5.0 and 2.5) getting 7.5

WJS
  • 36,363
  • 4
  • 24
  • 39
0

Just calculate it one by one:

  1. 10/4 == 2 (because of integer division)
  2. (double)2 == 2.0
  3. (int)10.0 == 10
  4. 2.0*10 == 20.0
  5. 20.0/4 = 5.0 (left part before +)
  6. (double)10 == 10.0
  7. 10.0/4 == 2.5 (right part after +)
  8. 5.0 + 2.5 = 7.5
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57