Search code examples
javaarraystype-conversionintegerconverters

How do I convert an Int to an Int[] in java?


I want to convert a primitive Java integer value:

int myInt = 4821;

To an integer array:

int[] myInt = {4, 8, 2, 1};

Solution

  • There can be so many ways to do it. A concise way of doing it's using Stream API as shown below:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int myInt = 4821;
            int[] arr = 
                String.valueOf(Math.abs(myInt)) // Convert the absolute value to String
                .chars()                        // Get IntStream out of the String
                .map(c -> c - 48)               // Convert each char into numeric value
                .toArray();                     // Convert the stream into array
    
            // Display the array
            System.out.println(Arrays.toString(arr));
        }
    }
    

    Output:

    [4, 8, 2, 1]
    

    Notes:

    1. ASCII value of '0' is 48, that of '1' is 49 and so on.
    2. Math#abs returns the absolute value of an int value
      • e.g. Math.abs(-5) = 5 and Math.abs(5) = 5