Devkinandan Chauhan
Devkinandan Chauhan

Reputation: 1935

Best way to cast int(primitive) to Long(wrapper) in Java

I have a primitive type int "pubNumber" in Java.

I want to convert it to "Long"(not primitive), As per my understanding, there are below ways to do the same.

1. Long.valueOf(pubNumber)
2. (long) pubNumber
3. new Long(pubNumber)

Can anyone please help me on which one is the best way to do the same and why?

Upvotes: 3

Views: 2268

Answers (3)

tread khuram
tread khuram

Reputation: 314

The difference between Long.valueOf(pubNumber) and new Long is that using new Long() you will always create a new object, while using Long.valueOf(), may return you the cached value of long if the value is between [-128 to 127].

So, you should prefer Long.valueOf method, because it may save you some memory.

Upvotes: 2

Eran
Eran

Reputation: 394156

You should avoid new Long(pubNumber), since that one will always create a new Long instance.

On the other hand, Long.valueOf(pubNumber) will return a cached Long instance if the value to be converted to Long is between -128 and 127.

(long) pubNumber should behave the same as Long.valueOf(pubNumber), since after the casting to long, it will be auto-boxed to Long, and I believe the auto-boxing of the long to Long uses Long.valueOf().

Upvotes: 4

Pritam Banerjee
Pritam Banerjee

Reputation: 18968

Long.valueOf(pubNumber) is the best way to do so because it uses values from cache if it is present.

Read here

public static Long valueOf(long l)
Returns a Long instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.

Parameters: l - a long value.
Returns: a Long instance representing l.
Since: 1.5

Upvotes: 3

Related Questions