How to convert int to array in java?

1 answer(s)
[]

A rather straightforward way to tackle this is by first converting the integer to a String. You can do this easily with String.valueOf(). Once you have the string, you can iterate over its characters.

For each character, convert it back into a number and place it in a new integer array. The Character.getNumericValue() method is perfect for this job.

If you are using Java 8 or newer, there is a much more elegant, one-line solution using streams. It is far more concise.

You can simply write: int[] digits = String.valueOf(number).chars().map(c -> c - '0').toArray();

This creates a stream from the string, maps each character to its integer value, and collects the result into an array. It’s clean and very modern.