Advertisement
Home Data Structure Arrays Convert Between int and Integer

Convert Between int[] and Integer[]

1
Advertisement

Title: Convert Between int[] and Integer[]

In this guide, you’ll learn how to convert a Java int[] array into an Integer[] array, and how to convert it back. This comes up constantly: the Collections API (List, Set, Map) only works with objects, so the moment you want numbers in a List<Integer> or need to pass them to a generic method, your primitive int[] has to become an Integer[] first.

Let’s explore why these two array types can’t simply be cast into each other, walk through a full working program that converts in both directions, trace it step by step, then cover the mistakes, edge cases, and interview follow-up questions that come up around array conversions.

Understanding the Problem

In Java, int is a primitive type and Integer is its wrapper class. An int[] is a compact block of raw 4-byte values, while an Integer[] is an array of references, each pointing to a separate Integer object on the heap. Because they are fundamentally different types, Java will not let you write (Integer[]) someIntArray; that cast simply fails to compile.

Autoboxing lets you assign a single int to an Integer variable (Integer n = 5;) and autounboxing lets you assign an Integer back to an int (int n = someInteger;), but neither conversion happens automatically at the array level. You have to convert each element yourself, either with an explicit loop or with the Stream API.

Approach

  1. Write a toIntegerArray(int[] source) method that allocates a new Integer[] with the same length as source.
  2. Loop over every index and assign result[i] = source[i]; the compiler autoboxes each int into an Integer on this assignment.
  3. Write a toIntArray(Integer[] source) method that allocates a new int[] with the same length as source.
  4. Loop over every index and assign result[i] = source[i]; the compiler autounboxes each Integer by calling intValue() internally.
  5. Call both methods from main on a sample int[], printing each result with Arrays.toString().
  6. Confirm the round trip, converting int[] -> Integer[] -> int[], returns values identical to the original array.

Java Program

Java
import java.util.Arrays;

public class ConvertIntAndInteger {

    public static Integer[] toIntegerArray(int[] source) {
        Integer[] result = new Integer[source.length];
        for (int i = 0; i < source.length; i++) {
            result[i] = source[i];
        }
        return result;
    }

    public static int[] toIntArray(Integer[] source) {
        int[] result = new int[source.length];
        for (int i = 0; i < source.length; i++) {
            result[i] = source[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] primitives = {4, 8, 15, 16, 23, 42};
        Integer[] boxed = toIntegerArray(primitives);
        System.out.println("Boxed array: " + Arrays.toString(boxed));

        int[] unboxed = toIntArray(boxed);
        System.out.println("Unboxed array: " + Arrays.toString(unboxed));
    }
}

Explanation of the Program

toIntegerArray walks the primitive array once, copying each element into the same slot of a new Integer[]. The assignment result[i] = source[i] is where autoboxing happens: the compiler rewrites it to result[i] = Integer.valueOf(source[i]) behind the scenes.

toIntArray performs the mirror operation. The assignment result[i] = source[i] autounboxes each Integer by calling source[i].intValue(), which throws a NullPointerException if that element is null.

main ties both directions together: it boxes a primitive array, prints it, unboxes it back, and prints that too, so you can see both conversions working on the same data.

Step-by-Step Trace

Here’s a dry run of toIntegerArray on a fresh input, int[] source = {5, 9, 3, 12, 7}, producing Integer[] {5, 9, 3, 12, 7}.

Iterationisource[i]result[i] (before)result[i] (after)
105null5
219null9
323null3
4312null12
547null7

At the end of iteration i, result[i] holds the boxed Integer equivalent of source[i], while every index greater than i still holds null because boxing happens one element per pass.

Examples

Example 1: Feeding a Boxed Array into a List

Collections only accept objects, so you need an Integer[] before you can hand the data to Arrays.asList().

Java
Integer[] boxed = {1, 2, 3};
List<Integer> list = Arrays.asList(boxed);
System.out.println(list); // [1, 2, 3]

Example 2: Converting with the Stream API

Boxing and unboxing can also be written as one-line stream pipelines if you prefer a more declarative style than the loop above.

Java
int[] source = {10, 20, 30};
Integer[] boxedStream = Arrays.stream(source).boxed().toArray(Integer[]::new);
int[] backToInt = Arrays.stream(boxedStream).mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(boxedStream)); // [10, 20, 30]
System.out.println(Arrays.toString(backToInt));   // [10, 20, 30]

Example 3: Unboxing a null Element

This is the failure case covered in Common Mistakes to Avoid below: an Integer[] with a null slot throws on unboxing.

Java
Integer[] withNull = {1, null, 3};
int[] result = toIntArray(withNull); // throws NullPointerException at index 1

Common Mistakes to Avoid

These are the mistakes that actually show up when converting between int[] and Integer[], not generic advice.

  • Casting the array directly – writing (Integer[]) someIntArray fails to compile because int[] and Integer[] are unrelated types; there is no cast between them. Convert element-by-element with a loop or stream instead.
  • Passing an int[] straight to Arrays.asList() – Arrays.asList(intArray) compiles but returns a single-element List<int[]>, not a List<Integer>, because generics cannot use primitive type parameters. Box the array into Integer[] first.
  • Unboxing a null Integer – calling toIntArray() on an Integer[] containing null throws NullPointerException the moment that element is unboxed. Check element != null before unboxing, or substitute a default value.
  • Comparing boxed values with == – Integer values outside the cached range of -128 to 127 are not reference-equal even when numerically equal, so a == b can silently return false after boxing. Use .equals(), or compare the unboxed int values instead.

Edge Cases to Test

Walk through these input shapes before calling the conversion done.

  • Empty array
  • Single-element array
  • Null array reference
  • Integer array containing one or more null elements
  • Values outside the Integer cache range (below -128 or above 127)
  • Integer.MIN_VALUE / Integer.MAX_VALUE present
  • Very large array (boxing overhead on memory)
  • Array of all identical values

Additional Considerations

Both conversion methods run in O(n) time and allocate O(n) extra space for the new array, since every element must be visited once to box or unbox it.

Boxing has a real memory cost. An int[] stores raw 4-byte values contiguously, but an Integer[] stores references, each pointing to a separate Integer object with its own object header. For a large array this can multiply memory use several times over. The JVM only caches Integer objects for the range -128 to 127 (via Integer.valueOf()), so values outside that range always allocate a fresh object.

The manual loop and the stream version do the same work. The loop is marginally faster and easier to debug, while the stream version reads more declaratively and composes well with other stream operations like filter or map. Pick whichever matches the surrounding code style.

Interview Follow-up Questions

Once you can convert the array in both directions, expect these variations:

  • What if the array contains null elements that must be preserved? – keep the target type as Integer[] instead of unboxing to int[], or replace each null with a sentinel value before unboxing.
  • Can you convert without allocating a brand new array? – no; int[] and Integer[] have different memory layouts at the bytecode level, so there is no in-place conversion, only a new array of the other type can hold the values.
  • How would you convert a 2D int[][] to Integer[][]? – apply the same per-element boxing loop one dimension at a time, converting each inner int[] row with toIntegerArray, or use nested streams.
  • What if the primitive values arrive as a stream too large to fit in memory? – use an IntStream pipeline and box elements only as they are consumed downstream, instead of materializing the full Integer[] up front.
  • What if boxing allocations are too costly in a performance-critical path? – lean on the Integer.valueOf() cache for values in -128 to 127, or avoid boxing entirely by keeping the data in a primitive-backed collection instead of an Integer[].

Conclusion

Converting between int[] and Integer[] comes down to one idea: box or unbox each element yourself, since Java will not do it for you at the array level. Once the loop (or stream) pattern is familiar, you can adapt it to any primitive/wrapper pair, long[]/Long[], double[]/Double[], and so on.

Try rewriting toIntegerArray and toIntArray as stream one-liners and compare the readability against the loop version to decide which style you would ship in production. You can learn more about array manipulation in the Arrays category on dailyjavaconcept.com.