Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an integer always be parsed as a long?

Tags:

java

types

I have a list of strings in Java which are being written to a text file. These strings are each tagged with a type -- in this case, I'll I'm interested are strings containing longs and ints. I'd like to convert these strings back to a numeric type before writing them, but I'd like to minimize code duplication. I plan on parsing every string tagged as an integer or long integer using Long.parseLong().

My question is this: are there any situations in which a valid integer will not parse as a long? I can't think of any (with the exception of maybe "1000L" or some such), but my experience in these matters has taught me that there are often nuances that I miss.

like image 227
Haldean Brown Avatar asked Dec 30 '25 02:12

Haldean Brown


2 Answers

Yes, integers can always be cast into long, but long cant always be cast into int.

An int is really a 4-byte whole number and a long is 8 bytes. So a long gives you 4 more bytes from an int.

like image 109
Chris Kooken Avatar answered Dec 31 '25 14:12

Chris Kooken


Long.parseLong("1000L") results in a NumberFormatException -- it accepts string-encoded numeric values, not necessarily Java number literals (although there is a large overlap).

Because of this Long.parseLong encompasses Integer.parseInt entirely just as the values of int are a proper subset of the values of long.

Happy coding.