Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long.decode and Long.parseLong

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?

like image 671
Taher Khorshidi Avatar asked Dec 08 '22 07:12

Taher Khorshidi


2 Answers

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).

like image 149
radar Avatar answered Dec 11 '22 09:12

radar


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
like image 45
Peter Lawrey Avatar answered Dec 11 '22 10:12

Peter Lawrey