Why this code prints 0? How do you make this code print 0.5 instead of 0?

Description:

final double d = 1 / 2;

System.out.println(d);

Solution:

The problem here is that this expression:

1 / 2

has integer literals on both sides of the operator: 1 and 2. As a consequence, an integer division will be performed, and the result of 1 divided by 2 in an integer division is 0.

In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:

final double d = 1 / 2.0;

or

final double d = 1.0 / 2;
0 answers