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

Suppose you lot receive got an int variable but the utilization of the application is expecting a Long object, how practise you lot convert a primitive int to a Long object inward Java? It shouldn't live a problem, right? afterward all long is a bigger information type than int, thence all int values are acceptable equally long, but nosotros likewise involve a Long object, non only the long primitive value. Now, the work is reduced to converting a long primitive to Long object, which is non actually a work if you lot are running on JRE version higher than Java 5. But, sometimes autoboxing is non efficient e.g. when you lot receive got to convert multiple long values into the Long object inward a loop. H5N1 improve way to convert your long primitive to the Long object is past times using static mill methods similar Long.valueOf(long l), which was originally meant to convert long primitive values to a Long object, prior to Java 5, but, likewise plant fine alongside int primitive.

So, if you lot receive got got an int primitive value, only exceed it to Long.valueOf() too you lot volition acquire a Long object alongside same value. BTW, This solely plant good if the method is expecting a long primitive value, if it's expecting a Long object thence you lot origin involve to cast an int to long, thence that autoboxing tin kick-in (see Java Fundamentals Part 1).

Autoboxing likewise has a disadvantage inward damage of converting cypher dorsum to primitive value e.g. if you lot receive got a Long object than it could live null but long primitive cannot live null. So auto-unboxing volition neglect alongside NullPointerException land converting a cypher Long object to long primitive. So you lot should beware of that. Now that you lot know to a greater extent than or less concepts, let's come across this conversion inward action.



int to Long - using autoboxing

In companionship to leverage autoboxing, you lot must typecast an int variable to long, otherwise, the compiler volition complain nearly mismatch type, equally shown below :

Long 1 = 10; // Type mismatch : cannot convert from int to Long
Long iii = (long) 3; // plant fine

Same is truthful for a method which is expecting a Long object. You cannot exceed an int to them because auto-boxing volition non live able to convert an int to Long (see Java Fundamentals: The Java Language), but, if you lot cast an int to long, thence auto-boxing volition convey attention of converting it to Long object, equally shown below :

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

for(int i=0; i< 10; i++){
    listOfLong.add((long)i);
}

So, if you lot desire to utilization autoboxing, brand certain you lot cast the int value to long first, don't worry though, if you lot forget compiler volition ensure this :)

Another matter to abide by inward higher upward code is that nosotros are using auto-boxing inward the loop, which tin drive functioning resultant because a lot of Long objects volition live created too discarded. In our case, it is notwithstanding ok because the loop is running solely 10 times, but if receive got to practise this conversion tell a 1000000 times, this approach volition drive a problem, equally explained past times Joshua Bloch inward his classic book, Effective Java. H5N1 must-read for whatever Java developer.




int to Long - using Long.valueOf()

One of the improve ways to convert an int primitive to the Long object is past times using the valueOf() method of the Long class. If you lot utilization Long.valueOf() thence you lot don't involve to explicitly cast an int to long, Why? because you lot tin exceed an int value to a method which is accepting primitive long.

Btw,  if you lot are non familiar alongside such key rules of Java programming, I advise taking the  Java Fundamentals: The Core Platform past times Jim Wilson, a gratis online preparation course of report from Pluralsight.
variable but the utilization of the application is expecting a  How to convert primitive int value to a Long object inward Java?


Since Long.valueOf() does receive got a long primitive, passing an int value to it is no work at all, hither you lot acquire :

// you lot tin exceed an int to method expects long
Long 2 = Long.valueOf(2); //Ok

It's seamless, build clean too easy. It is likewise efficient because valueOf() method implement Flyweight blueprint (see Design Patterns Library) too maintains a puddle of oftentimes used Long values, peculiarly inward the make of -128 to 127, equally shown below. Since Long is likewise immutable inward Java, it's no impairment sharing same Long instance betwixt multiple clients.

The Long.vlaueOf() method from JDK 8:

 public static Long valueOf(long l) {
        lastly int offset = 128;
        if (l >= -128 && l <= 127) { // volition cache
            render LongCache.cache[(int)l + offset];
        }
        render novel Long(l);
    }

You tin come across it caches the Long instances alongside values inward the rage of -128 to 127. This way same Long instance is returned to multiple clients too this operate because similar String, Long is likewise Immutable inward Java.  So, it's prophylactic to percentage the same instance of the Long object betwixt multiple clients.

That's all nearly how to convert a primitive int value to a Long object inward Java. It's slowly but worth knowing the subtleties involved. Prefer Long.valueOf() to convey wages of caching it provides equally good equally to avoid casting. Also, retrieve that auto-boxing volition throw NPE if you lot desire to convert a Long object dorsum to long primitive value too it happened to live null. This form of NPE is sometimes non obvious too takes a long fourth dimension to reveal itself.

If you lot similar this tutorial too interested inward learning nearly information type conversion inward Java, depository fiscal establishment check out these amazing tutorials :
  1. How to convert Map to List inward Java (tutorial)
  2. How to convert Double to Long inward Java? (tutorial)
  3. How to convert Array to String inward Java? (tutorial)
  4. 5 Ways to convert Java 8 Stream to List? (solution)
  5. How to convert a binary let out to decimal inward Java? (tutorial)
  6. 5 examples of converting InputStream to String inward Java? (tutorial)
  7. How to convert Character to String inward Java? (tutorial
Thanks for reading this tutorial, if you lot similar this article thence delight percentage alongside your friends too colleagues, it makes a lot of difference.

Subscribe to receive free email updates:

0 Response to "How to convert primitive int value to a Long object inwards Java?"

Posting Komentar