Java
int[] to Integer[]
Array Conversion
Java Programming
Code Example

How can I convert int to Integer in Java?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Converting an int[] to an Integer[] in Java is a common task that may arise when you need to work with collections or APIs requiring objects rather than primitives. Java's autoboxing is a powerful feature that facilitates this conversion process. This article provides an in-depth understanding of the methodologies for performing such conversions, including technical explanations and illustrative examples.

Understanding Primitives and Objects in Java

Java is a strongly-typed language that distinguishes between primitive types (e.g., int, double, char) and reference types (e.g., Integer, Double, Character). Primitives are basic data types anchored in simplicity and performance, while reference types are objects that offer utility methods and additional functionalities.

Why Convert?

The conversion from int[] to Integer[] might be necessary for several reasons:

  • API Requirements: Many Java Collections Framework classes, such as ArrayList, require elements to be objects.
  • Null Handling: Primitives cannot represent null, which can be useful in some contexts.
  • Object Methods: Invoke methods available in wrapper classes, like Integer.

Conversion Methods

1. Manual Loop

This method involves iterating through the int[] and manually boxing each element into an Integer.

java
1public Integer[] convertIntArrayToIntegerArray(int[] inputArray) {
2    Integer[] integerArray = new Integer[inputArray.length];
3    for (int i = 0; i < inputArray.length; i++) {
4        integerArray[i] = inputArray[i]; // Autoboxing
5    }
6    return integerArray;
7}

Explanation

  • Autoboxing: Java automatically converts a primitive data type to its corresponding wrapper class, e.g., int to Integer.

2. Using Streams (Java 8 and Above)

Java 8 introduced streams, which offer a functional approach to perform operations on collections or arrays.

java
1public Integer[] convertIntArrayToIntegerArrayUsingStreams(int[] inputArray) {
2    return java.util.Arrays.stream(inputArray)  // Generate an IntStream
3            .boxed()                            // Convert each element to Integer
4            .toArray(Integer[]::new);           // Collect as Integer[]
5}

Explanation

  • Stream: Allows operations on sequences of elements including those derived from int[].
  • Boxed: Converts each element of an IntStream to an Integer.
  • Method References: Integer[]::new is a constructor reference.

3. Apache Commons Utils

For developers who prefer leveraging existing libraries, Apache Commons Lang provides a utility method.

java
1import org.apache.commons.lang3.ArrayUtils;
2
3public Integer[] convertIntArrayToIntegerArrayUsingApacheCommons(int[] inputArray) {
4    return ArrayUtils.toObject(inputArray);
5}

Explanation

  • ArrayUtils.toObject: A utility method dedicated to converting primitive arrays to object arrays.

Performance Considerations

When dealing with large arrays, the performance of these methods can vary:

  • Manual Loop: Offers fine-grained control, generally has minimal overhead but requires boilerplate code.
  • Streams: Excellent for readability and expressiveness but may introduce overhead due to stream processing.
  • Third-Party Libraries: Eases development time but requires additional dependencies.

Summary Table

Below is a table summarizing the various conversion methods:

MethodPerformanceReadabilityNotes
Manual LoopHigh performanceModerateBest when performance is a critical need
StreamsModerate performanceHighFunctional approach with ease of use
Apache Commons UtilModerate performanceHighUtilizes ArrayUtils

Additional considerations, such as error handling, null safety, and compatibility with older Java versions (for methods like Streams), should also be evaluated based on your specific application needs.

Conclusion

Converting int[] to Integer[] has multiple approaches, each with its strengths and trade-offs. Whether you're building a legacy application or working with modern Java features, the method you choose should align with your project requirements, performance expectations, and code readability preferences. Understanding these conversion mechanisms empowers developers to handle such tasks effectively and efficiently, prioritizing both the codebase maintenance and operational excellence.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.