1

I am using Java 1.6 final double check = 3 / 4; System.out.println(check);

Console is showing: 0.0

Why is this happening? Shouldn't it come out 0.75?

user3494047
  • 1,643
  • 4
  • 31
  • 61

4 Answers4

3

Make that:

double check = 3.0 / 4;

and it'll work. You got 0 because 3 / 4 is an integer division, whose value is 0.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

Because both are integer hence result will also be integer.

Cast any one into double like this:

double check = (double)3 / 4;
Braj
  • 46,415
  • 5
  • 60
  • 76
0

By doing:

3 / 4

you are performing an integer division, since 3 and 4 are int constants, not doubles. The result is therefore an int. But since you are assigning it to a double, the result of the division will then be promoted to a double. But at this point it is too late, since the integer division will have produced 0!

You need to do:

3.0 / 4

to achieve your desired result, since in this case, 4 will automatically be promoted to a double, and the result of the division will also be a double.

To be perfectly sure of what happens and if you like symmetry, you can also write:

3.0 / 4.0
fge
  • 119,121
  • 33
  • 254
  • 329
0

You are dividing integers and assigning the result to double.In java division of two int values always yields an int.
So change the statement double check = 3 / 4; to double check = 3.0 / 4;

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24