Java primitives conversion & operations

First, booleans

Booleans cannot be assigned to any other types, and you can't do any arithmetic on them. So true doesn't count as 1, nor does 1 count as true. No truthy and falsy in Java.

Converting: a = b

Some types can only be converted if you cast explicitly. These are usually the cases where a type with a wider or different range is converted to one with a narrower range. If you use explicit casting, you might be changing to a nonsense value if it's outside the range of the target.

from / into byte short char int long float double
byte implicit explicit implicit implicit implicit implicit
short explicit explicit implicit implicit implicit implicit
char explicit explicit implicit implicit implicit implicit
int explicit explicit explicit implicit implicit implicit
long explicit explicit explicit explicit implicit implicit
float explicit explicit explicit explicit explicit implicit
double explicit explicit explicit explicit explicit explicit

Arithmetic: a + b

This table shows the output for arithmetic operations between two variables. For example, long * float becomes a float.

  byte short char int long float double
byte integer integer integer integer long float double
short integer integer integer integer long float double
char integer integer integer integer long float double
int integer integer integer integer long float double
long long long long long long float double
float float float float float float float double
double double double double double double double double

Integers versus decimals

Note that this does not mean that information cannot be lost! For example, Long.MAX_VALUE = 9223372036854775807, but when stored as a float it is approximated as 9223372036854776000 in a float: a big difference.

float and double don't have uniform spacings between adjacent representable values. Low values are much closer together than high values. The spacing between two values that can be represented exactly is much greater than 1 for high values (so a + 1.0 might be a if it is a float or double). You might have expected this, since a int has 4 bytes with range from -2^31 to +2^31-1 possible values, where float also has 4 bytes but has a much bigger range (2^(2^7) = 3.4e38). Obviously it cannot store all the numbers that integer can, there aren't enough bytes (and that ignores non-integer numbers).

So what this means, is that although you can store integers are decimals without explicit casting, you might still lose precision for higher integers.

Image of assignment of primitives in Java: some need explicit casting, some are implicit, and boolean is incompatible.

Image of arithmetic results in Java: operations follow integer < long < float < double.

Comments

No comments yet

You need to be logged in to comment.