Why double = 5/2 is 2.0 in java? Why it is not 2.5? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why double = 5/2 is 2.0 in java? Why it is not 2.5?

Int a = 5 Int b = 2 Double result = 5/2 Out put is 2.0????????🤔

12th Sep 2019, 11:17 PM
Abman
Abman - avatar
5 Answers
+ 5
Game Station Like I said, it's because the division is evaluated first, the result of 5/2 is an integer, because it's integer division, because of that the result is 2. The number 2 is an integer, but it's supposed to be double, so that number is casted to double which result in 2.0. If you want double as the result, you should change one of the number to double (5/2.0 or 5.0/2 or 5.0/2.0)
12th Sep 2019, 11:32 PM
Agent_I
Agent_I - avatar
0
It's because 5/2 is evaluated first. The result of that division is 2, and then that result is casted to double and become 2.0
12th Sep 2019, 11:20 PM
Agent_I
Agent_I - avatar
0
Double shows decimles then why it is not 2.5? 🤔
12th Sep 2019, 11:26 PM
Abman
Abman - avatar
0
Thanks
12th Sep 2019, 11:49 PM
Abman
Abman - avatar
0
Double is 8 bytes and integer is 4 bytes. If you do 4.0/ 2 the result will be 2.0 because compiler will impilicitly cast that result into double because it cares about bytes and dont wanna lose it. You can do (int) 4.0 / 2 to get 2 this is called explicit type casting because compiler will know to cast it into integer and lose bytes due to your command. Hint: Compilers dont like to lose bytes during arithmetic operations so it will pick the biggest data type to not lose
13th Sep 2019, 9:20 AM
Talha Altınel (The Last Sith Lord)
Talha Altınel (The Last Sith Lord) - avatar