How to convert int value to a Long object in Java? Examples

Suppose you have an int variable but the part of the application is expecting a Long object, how do you convert a primitive int to a Long object in Java? It shouldn't be a problem, right? after all long is a bigger data type than int, so all int values are acceptable as long, but we also need a Long object, not just the long primitive value. Now, the problem is reduced to converting a long primitive to a Long object, which is not really a problem if you are running on a JRE version higher than Java 5. But, sometimes autoboxing is not efficient like when you have to convert multiple long values into the Long object in a loop. 

A better way to convert your long primitive to the Long object is by using static factory methods like Long.valueOf(long l), which was originally meant to convert long primitive values to a Long object, prior to Java 5, but, also works fine with int primitive.

So, if you have got an int primitive value, just pass it to Long.valueOf() and you will get a Long object with same value.

Btw, This only works well if the method is expecting a long primitive value, if it's expecting a Long object then you first need to cast an int to long, so that autoboxing can kick-in 

Autoboxing also has a disadvantage in terms of converting null back to primitive value e.g. if you have a Long object than it could be null but long primitive cannot be null.

So auto-unboxing will fail with NullPointerException while converting a null Long object to long primitive. So you should beware of that. Now that you know some concepts, let's see this conversion in action.


2 Examples to convert an int to a long data type in Java

Here is our two main examples for convert an int data type value to a long data type value. Remember, int is a smaller type and long is bigger data type as int require only 4 bytes or 32-bit as compared to 8 bytes and 64-bit required by long data type. 

1. int to Long in Java - using autoboxing

In order to leverage autoboxing, you must typecast an int variable to long, otherwise, the compiler will complain about mismatch type, as shown below :

Long one = 10; // Type mismatch : cannot convert from int to Long
Long three = (long) 3; // works fine

Same is true for a method which is expecting a Long object. You cannot pass an int to them because auto-boxing will not be able to convert an int to Long (see The Complete Java Masterclass - Update for Java 11), but, if you cast an int to long, then auto-boxing will take care of converting it to Long object, as shown below :

List<Long> listOfLong = new ArrayList<Long>();

for(int i=0; i< 10; i++){
    listOfLong.add((long)i);
}
So, if you want to use autoboxing, make sure you cast the int value to long first, don't worry though, if you forget compiler will ensure this :)

Another thing to notice in the above code is that we are using auto-boxing in the loop, which can cause performance issue because a lot of Long objects will be created and discarded.

In our case, it is still ok because the loop is running only 10 times, but if have to do this conversion say a million times, this approach will cause a problem, as explained by Joshua Bloch in his classic book, Effective Java 3rd Edition. A must-read for any Java developer.



2. int to Long - using Long.valueOf()

One of the better ways to convert an int primitive to the Long object is by using the valueOf() method of the Long class. If you use Long.valueOf() then you don't need to explicitly cast an int to long, Why? because you can pass an int value to a method which is accepting primitive long.

Btw,  if you are not familiar with such fundamental rules of Java programming, I suggest taking these free Java online training courses from Udemy and Pluralsight.

How to convert primitive int value to a Long object in Java?


Since Long.valueOf() does accept a long primitive, passing an int value to it is no problem at all, here you go :

// you can pass an int to method expects long
Long two = Long.valueOf(2); //Ok

It's seamless, clean and easy. It is also efficient because valueOf() method implement Flyweight pattern (see Design Patterns courses) and maintains a pool of frequently used Long values, particularly in the range of -128 to 127, as shown below.

Since Long is also immutable in Java, it's no harm sharing same Long instance between multiple clients.

The Long.vlaueOf() method from JDK 8:
public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

You can see it caches the Long instances with values in the rage of -128 to 127. This means same Long instance is returned to multiple clients and this work because like String, Long is also Immutable in Java.  So, it's safe to share the same instance of the Long object between multiple clients.

That's all about how to convert a primitive int value to a Long object in Java. It's easy but worth knowing the subtleties involved. Prefer Long.valueOf() to take advantage of caching it provides as well as to avoid casting.

Also, remember that auto-boxing will throw NPE if you want to convert a Long object back to long primitive value and it happened to be null. This kind of NPE is sometimes not obvious and takes a long time to reveal itself.


Further Learning
Top 5 Java Programming courses for beginners
3 books to learn Java from scratch
Top 5 Websites to learn Java for FREE

If you like this tutorial and interested in learning about data type conversion in Java, check out these amazing tutorials :
  1. How to convert Map to List in Java (tutorial)
  2. How to convert Double to Long in Java? (tutorial)
  3. How to convert Array to String in Java? (tutorial)
  4. 5 Ways to convert Java 8 Stream to List? (solution)
  5. How to convert a binary number to decimal in Java? (tutorial)
  6. 5 examples of converting InputStream to String in Java? (tutorial)
  7. How to convert Character to String in Java? (tutorial

Thanks for reading this tutorial, if you like this article then please share with your friends and colleagues, it makes a lot of difference.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.