Int division: Why is the result of 1/3 == 0?
In integer division, fractions are merely discarded. For decimals in your result, cast to double
:
With 3.0
, we've got floating-point division in action here.
Understanding integer division
When two integers divide, Java thinks they're at a whole numbers party and promptly performs integer division. Unfortunately, this party doesn't have fractional nibbles, so any fractional part is discarded:
Float over to the floating-point types (double
, float
) to keep fractions while serving up division.
Casting for accurate division
Making integers float, or explicit casting to double
or float
, brings fractions to our division party:
Casting 1
to double
changes the party theme from integer to floating-point. For variable party-goers (not literals), employ this:
Factoring in Binary Numeric Promotion
Java's got some strict Binary Numeric Promotion rules that it invites to every operation:
- If
double
is a guest, everyone else also has to bedouble
. - If there's no
double
, butfloat
is invited, everyone else upgrades tofloat
. - If neither
double
norfloat
could make it, butlong
is there, then everyone becomeslong
. - If
double
,float
, andlong
didn't show, everyone else is thenint
.
Invite literals with decimals, and they will automatically bring the double
division:
Operand conversion decoded
To avoid any division disappointment, it's good to keep an eye on operand conversion before the operation:
- Know your operand types before the operation — beforehand check-in can save the party from integer division disaster.
- Note the difference between implicit and explicit casting.
- Be aware that widening conversions might swoop in when different types mingle.
Keeping the numbers precise
For high precision, the BigDecimal class is the elite guest you want at your party:
Integer vs Floating-Point Division: Knowing when
- Use integer division when all you need is the whole part.
- Floating-point division makes the cut when you need a dash of decimals in your results.
Coding pitfalls and quick hacks
- Lost in conversion: Casting your variables explicitly can save you from a botched division operation.
- Precision is key: If precision can make or break your operation, get
BigDecimal
on board. - Literal confusion:
1.0
is adouble
type, and1f
is afloat
. Get your literal act straight!
Dealing with different scenarios
Results change depending on the types involved. For instance:
Two integer variables:
Integer and double literals:
Type casting an integer:
Using BigDecimal for precision:
Was this article helpful?