Be clear that you are mixing 32-bit values and 64-bit numbers. So you need to work towards ending up with the bigger 64-bit results t avoid losing data.
And be aware that you are mixing integer numbers with fractional numbers.
On both issues above, study carefully how Java primitives syntax works with numeric literals.
So yes you can mix the types. Java will generally do the right thing. For example, multiplying a long
by an int
will produce a long
. But there are cases in complicated code where the compiler may get confused, and you will need to add some explicit casts such as ( long )
. Any basic intro-to-Java book or the Oracle Tutorial will walk you though this.
Tips:
- Append an
L
to long
literals.
- Append
f
to float
literals. And d
to double
literals.
- Use underscores to group your digits for easier reading. Ex:
1_000_000
Lastly, be aware that float
and double
are both floating-point numbers. Floating-point technology trades off accuracy for performance. This is good for rendering curves in a drawing or rendering a game, but bad for money or other values where you don't want extraneous extra digits in your decimal fraction.
BigDecimal
If accuracy matters, I would convert all your values to BigDecimal
objects rather than primitives. BigDecimal
eschews floating-point. Much slower, but accurate.