In a test I see that Long.decode work similar to Long.parseLong for simple number format strings (i mean strings without '0x' ,...).
System.out.println(Long.decode("123") + Long.decode("123")); // prints 246
System.out.println(Long.parseLong("123") + Long.parseLong("123")); // same as above
can I use Long.decode instead of Long.parseLong anywhere? if not why?
They will both act similarly, but Long.parseLong returns a primitive long whereas Long.decode returns a new Long object, which takes more time and resources. So, it's probably best to use Long.parseLong for simple cases. But, Long.decode provides more flexibility as it will allow you to decode inputs that are hex (e.g. 0xFFFF), or octal (e.g. 010 == 8).
You can't use decode() if your numbers might start with a 0 and you don't want this to be octal.
e.g.
Integer.decode("010") == 8 // octal
Integer.parseInt("010") == 10 // always decimal
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