Convert Char Array to Int Array in Java
One common task we could encounter is converting character arrays to integer arrays. There are several ways to convert a character array containing digits (char[]
) into an integer array (int[]
) in Java. In this guide, we will explore different techniques to accomplish this task.
1. Using Character.getNumericValue()
Java provides a built-in method Character.getNumericValue(char)
that returns the numeric value of the character as an integer.
This method iterates through the character array and converts each character to its corresponding integer value.
- Loop through each character in the char array.
- Use
Character.getNumericValue(char)
to get the integer value (0-9) for the character. If the character isn’t a digit, -1 is returned. - Handle non-numeric characters appropriately (e.g., throw an exception).
- Build the resulting integer array by storing the converted values.
Code Example:
public class CharToIntArrayGetNumericValues { public static int[] charArrayToIntArray(char[] charArray) { int[] intArray = new int[charArray.length]; for (int i = 0; i < charArray.length; i++) { int digit = Character.getNumericValue(charArray[i]); if (digit == -1) { // Handle non-numeric character throw new IllegalArgumentException("Input contains non-numeric characters"); } intArray[i] = digit; } return intArray; } public static void main(String[] args) { char[] charArray = {'1', '2', '3', '4'}; int[] intArray = charArrayToIntArray(charArray); // Print out the int array System.out.println("Converted Integer Array:"); for (int number : intArray) { System.out.print(number + " "); } } }
When you run this code, it will print out the converted integer array:
2. Using Integer.parseInt()
Since the characters in the array represent digits, you can also use Integer.parseInt(String)
to convert individual characters to integers by first converting them to strings.
Example:
public class CharToIntArrayParseInt { public static int[] charArrayToIntArray(char[] charArray) { int[] intArray = new int[charArray.length]; for (int i = 0; i < charArray.length; i++) { intArray[i] = Integer.parseInt(String.valueOf(charArray[i])); } return intArray; } public static void main(String[] args) { char[] charArray = {'1', '2', '3', '4', '5'}; int[] intArray = charArrayToIntArray(charArray); // Print out the int array System.out.println("Converted Integer Array:"); for (int number : intArray) { System.out.print(number + " "); } } }
In the code above, we use the Integer.parseInt(String.valueOf(charArray[i]))
method to convert the String representation of the digits to an integer.
3. Using Stream API (Java 8+)
Java’s Stream API provides concise and efficient ways to manipulate collections. Leveraging the Stream API can offer elegant solutions when converting character arrays to integer arrays.
- Create a stream of integer values from the character stream using
chars()
andmap()
. - Subtract 48 from each character to convert Unicode values (48 for ‘0’, 49 for ‘1’, etc.) to actual integer values. Note: Subtracting an integer from a char automatically casts the
char
toint
returning its Unicode value in decimal format. - Collect the stream into an integer array using
collect(Collectors.toIntArray())
.
Code Example (Java 8+):
public class CharToIntArrayStreams { public static int[] charArrayToIntArray(char[] charArray) { return new String(charArray).chars() .map(c -> c - 48) .toArray(); } public static void main(String[] args) { char[] charArray = {'1', '2', '3', '4'}; int[] intArray = charArrayToIntArray(charArray); System.out.print("Integer array: "); for (int number : intArray) { System.out.print(number + " "); } } }
4. Using Unicode Values
One straightforward approach to converting a character array to an integer array is by utilizing the Unicode values of characters. In Java, characters are internally represented as Unicode code points, and each character has a corresponding Unicode value. Since digits have successive Unicode values, by subtracting the Unicode value of ‘0’ (48) from the values of other digit representing characters, we can obtain their integer equivalents. This approach is equivalent to the previous one, prefer it when Java Streams are not available.
Example:
public class CharToIntArrayASCII { public static int[] charArrayToIntArray(char[] charArray) { int[] intArray = new int[charArray.length]; for (int i = 0; i < charArray.length; i++) { intArray[i] = charArray[i] - '0'; } return intArray; } public static void main(String[] args) { char[] charArray = {'1', '2', '3', '4', '5'}; int[] intArray = charArrayToIntArray(charArray); // Print out the int array System.out.println("Converted Integer Array:"); for (int number : intArray) { System.out.print(number + " "); } } }
5. Choosing the Right Approach
- If you need a simple solution and are confident the input only contains digits,
Integer.parseInt
is a quick option. - For more control and error handling,
Character.getNumericValue
allows us to handle non-numeric characters gracefully. - Java Streams offers a concise and potentially more performant approach for Java 8 and above.
Remember to consider the specific requirements of your application when selecting the most suitable method.
6. Conclusion
By understanding the methods outlined in this guide, you can choose the most suitable approach based on your requirements. Whether you opt for the Stream API, use built-in methods like Character.getNumericValue()
, or leveraging Integer.parseInt()
, Java provides flexibility and efficiency in handling such conversions.
7. Download the Source Code
This was an example of how to Convert Char Array to Int Array in Java.
You can download the full source code of this example here: Convert Char Array to Int Array in Java