Can an integer be treated as long?

I have a list of lines in Java that are written to a text file. Each of these lines is labeled type - in this case, I'm interested in lines containing longand ints. I would like to convert these strings back to a numeric type before writing them, but I would like to minimize code duplication. I plan on parsing every line marked as an integer or a long integer using Long.parseLong().

My question is this: are there situations where a real integer will not be parsed as a long one? I can't think of a single one (with the possible exception of “1000L” or some of these), but my experience in these matters has taught me that there are often nuances that I miss.

+3
source share
5 answers

Yes, integers can always be assigned to long numbers, but long ones will not always be cast in int.

int is really a 4-byte integer, and long is 8 bytes. So long gives you 4 more bytes from int.

+6
source

Long.parseLong("1000L") throws a NumberFormatException - it takes string values, not necessarily Java literals (although there is a lot of overlap).

Because of this, Long.parseLongcovers are Integer.parseIntcompletely the same as values intare the correct subset of values long.

Happy coding.

+3
source

, ints - longs.

+1

- ( , l L )

0

int long double ( BigInteger)

0
source

All Articles