Reputation: 924
long is a 64-bit signed two's complement integer. Is Long a 128-bit signed two's complement integer? I just wanted to confirm this before proceeding.
Long l = 6;
int i = 4;
Integer ii = 2;
l += (l/i) * ii;
I was wondering where I would need to typecast in order to get back 3, instead of 2.
I tried the following:
l += (long) (((double) l/i) * ii);
When I typecast l/i
with double
, I get back 1
, instead of 1.5
?
Lets say I was to typecast a Long, that was the largest number for a Long, with (long), what would happen since long is a 64-bit signed two's complement integer.
Upvotes: 2
Views: 143
Reputation: 3191
Your (l/i) * ii
means power? If so, maybe you should use BigDecimal
. By the way, 1/i
equals 0; use 1.0/i
instead.
Upvotes: 0
Reputation: 14313
long
(lower case) is a primitive type 64-bit integer. Long
(upper-case) is a reference type (object) that wraps a long
(lower-case). So Long
's encode their data in a long
and are hence 64-bit as well. If you want > 64-bit precision, look into java.math.BigInteger which offers arbitrarily high precision.
Your problem does not come from incorrect casting within the division statement but from the cast to long
at the end:
l += (long) (((double) l/i) * ii);
^
here
The result of (((double) l/i) * ii)
is a double
of value 3.0. Due to the peculiarities of floating-point arithmetic, this becomes 2 when it is cast to a long
.
In order to solve this, use Math.round
instead of a typecast:
l += Math.round(((double) l/i) * ii);
Upvotes: 4
Reputation: 15642
Long
is a class containing constructors, methods, and constants relevant to the long
primitive object (eg. Long.MAX_VALUE
which will give you the maximum value that a long
can represent). When you convert a long
to a Long
, you're converting from a value type to a reference type. The number of bits used to represent the values won't change.
Upvotes: 0