I’m consolidating code written by two different people and notice that casting a String value into a Long has been done in two different ways.
Coder #1 has done this:
String strId = "12345678";
...
Long lId = new Long(strId);
While coder #2 has done this:
String strId = "12345678";
...
Long lId = Long.valueOf(strId);
Functionally, the code operates exactly the same. There’s a try/catch block around each bit to handle any NumberFormatException that is thrown. The incoming string value is an 8 digit string that represents a decimal: "12345678" and in both cases it is correctly converted into Long.
Is there any functional difference between passing the string in the constructor and using Long.valueOf()? I’ve checked the constructor doc here:
and the docs for valueOf() here:
Long.valueOf(java.lang.String)
As far as I can tell, they both call parseLong() so it doesn’t matter which is used. I just want to make sure I’m not setting myself up for some strange behavior further down the road. Also, is either style more “correct” (haha) than the other?
The difference is that using
new Long()you will always create a new object, while usingLong.valueOf(), may return you the cached value oflongif the value is between[-128 to 127].So, you should prefer
Long.valueOfmethod, because it may save you some memory.If you see the source code for
Long.valueOf(String), it internally invokesLong.valueOf(long), whose source code I have posted below: –