Explain Codes LogoExplain Codes Logo

Converting Integer to Long

java
casting
null-handling
performance-optimization
Alex KataevbyAlex Kataev·Aug 27, 2024
TLDR

Convert Integer to Long in Java with longValue():

Integer myInt = 123; Long myLong = myInt.longValue(); // Straightforward conversion method

Or leverage auto-boxing for a cleaner syntax:

Long myLong = myInt.longValue(); // The Java compiler is feeling generous today

Both cases produce a Long identical in value to the Integer.

Conversion pitfalls and principles

Direct casting from Integer to Long is not allowed in Java. It's entirely discouraged to solely rely on casting:

Integer myInt = 123; // Long myLong = (Long) myInt; // Java says "Nope!"

Working with corner cases

Null handling and type checking

Ensure Integer objects are not null, and are indeed an Integer. This pre-emptive measure avoids NullPointerException or ClassCastException:

if (myInt != null && myInt instanceof Integer) { Long myLong = myInt.longValue(); // Safety first, conversion second }

Array conversions

For array conversions, use Java's Stream API to efficiently convert an Integer array to a Long array:

Integer[] integerArray = {1, 2, 3}; Long[] longArray = Arrays.stream(integerArray).map(Integer::longValue).toArray(Long[]::new); // Streams make things flow smoothly

Performance considerations

Long.valueOf() can cache small integer values and could offer better performance for such cases:

Integer myInt = 10; Long myLong = Long.valueOf(myInt.intValue()); // It's not about size, but efficiency!

Avoid redundant conversions

Avoid transformations through strings to maximize efficiency. String parsing could have a superfluous performance impact:

// Inefficient method - Extra string conversion with no added flavor Long myLong = Long.parseLong(myInt.toString());

Advanced conversion methods

Reflection conversions

Rarer instances might include reflection conversions, but relevant type checks are essential:

Field field = myObject.getClass().getDeclaredField("myIntField"); if (field.getType().equals(Integer.class)) { Integer intValue = (Integer) field.get(myObject); Long longValue = intValue.longValue(); // No mirrors involved in this reflection }

Understanding your limit

The range between Integer (±2.1 billion) and Long (±9.2 quintillion) is significant. Always remember that Integer will fit into Long, but not vice versa -- it's not a casual one-size-fits-all situation!