2

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!

ReNiSh AR
  • 2,782
  • 2
  • 30
  • 42
user2917239
  • 898
  • 3
  • 12
  • 27

5 Answers5

7

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);
Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
5

You trying to divide 5 by 9.Both are integers.So the answer is also an integer.So return 0 as answer.So try like System.out.println(5.0/9); or assign values to float variables and go with that

Adarsh M Pallickal
  • 813
  • 3
  • 16
  • 37
3

Integer divide by Integer returns Integer

Do like this

System.out.println(5.0/9);
Nambi
  • 11,944
  • 3
  • 37
  • 49
2

This is an integer division because both operands are of type integer. An integer division gives an integer result obtained by truncation.

Henry
  • 42,982
  • 7
  • 68
  • 84
2

When Integer division is ran in Java (Integer / Integer), the number is calculated then rounded down to the while number. Therefore, 5/9 is evaluated as 0.55555 then rounded down to 0.

Adam
  • 2,532
  • 1
  • 24
  • 34