Java Char Array to Integer Array

There may be times as a Java developer that you will need to convert a Char Array to Integer Array. This task can be accomplished in a few simple steps in Java.

Start off my defining a String of random numbers. Convert that String to a Char Array. Define a new Integer Array with the size of the initial String. Finally, you can assign values from the Char Array to the Integer Array using a standard for loop. Take a look at the sample Java code below.

Java Char Array to Integer Array Source Code


import java.util.Arrays;

public class JavaCharArrayToIntArray {
	//Java Code Depot Sample

	public static void main(String[] args) {

		//Start with a string of numbers
		String jcdString = "0123456789";
		//Convert the string of numbers to a character array
		char[] jcdCharArray = jcdString.toCharArray();
		//Define an integer array based on length of original string
		int[] jcdIntegerArray = new int[jcdString.length()];

		//Loop through each element of char array to the integer array
		for (int i = 0; i < jcdString.length(); i++) {
			jcdIntegerArray[i] = (int)jcdCharArray[i] - 48;



Java Char Array to Integer Array Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Add a Comment

Your email address will not be published. Required fields are marked *