Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Java division print out zero? [duplicate]

Tags:

java

I have the following line of code:

System.out.println(5/9);

I expect to see 0.555 as a result, but instead it prints out zero. Can someone help me understand why this happens? I am currently learning programming and appreciate the help.

Thanks!

like image 888
user2917239 Avatar asked Jul 30 '26 13:07

user2917239


1 Answers

This happens because what you are unknowingly doing is Integer Division. To make calculations fast, computer uses Integer division method when there's no decimal number involved, and hence decimal values are lost.

Try this out:

System.out.println(5.0 / 9.0);

or

System.out.println(5.0 / 9);

or

System.out.println(5 / 9.0);

or

System.out.println((float) 5 / 9);

or

System.out.println(5 / (float) 9);
like image 198
Aman Agnihotri Avatar answered Aug 04 '26 20:08

Aman Agnihotri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!