0

I have two statements in java:

System.out.println(2 * (5 / 2 + 5 / 2 ));

This generate the output 8 but again in next line:

System.out.println(2 * 5 / 2 + 2 * 5 / 2 );

This generate the output 10.

now my confusion is why it generates different output

please someone describe it. thanks

Andronicus
  • 25,419
  • 17
  • 47
  • 88
MEERA
  • 35
  • 2
  • 2
    you execute two different statements and you are confused you get a different output? why? forget about programming, think maths and order of executions. try to calculate and check why it is different – Stultuske Mar 27 '20 at 13:30
  • 2
    There's no floats. You're doing integer division. – Kayaman Mar 27 '20 at 13:31

1 Answers1

1

Note, that division between ints generates an int (rounded down).

2 * (5 / 2 + 5 / 2) => 2 * (2 + 2) => 8

2 * 5 / 2 + 2 * 5 / 2 => 10 / 2 + 10 / 2 => 10

To get the exact value, you would have to use floats:

2 * (5.0 / 2 + 5.0 / 2) == 10
Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • according to `bodmas` rule, divide get execute first, I thought it should be `2 * 5 / 2 + 2 * 5 / 2 => 2*2 + 2*2 => 8` – MEERA Mar 27 '20 at 13:40