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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With