Converting a String Array to an Int Array in Java

06 May 2023 Balmiki Mandal 0 Core Java

Converting a String Array Into an int Array in Java

In some instances, it might be necessary to convert a string array into an int array. This article will show you how to make this conversion in Java. We will demonstrate two different methods for achieving this conversion.

Method 1: Using parseInt() and Integer wrapper class

The easiest way to convert a string array into an int array is to use the parseInt() method and Integer wrapper class. The parseInt() method accepts a String object and converts it into an int value. You can then use the Integer class to wrap the int value into an Integer object. Here is an example of how to do this:

String[] strArray = {"12", "15", "23"}; 

int[] intArray = new int[strArray.length]; 

for(int i=0 ; i<strArray.length ; i++) { 
    intArray[i] = Integer.parseInt(strArray[i]); 
} 

Method 2: Using valueOf() and Integer wrapper class

Another way to convert a string array into an int array is to use the valueOf() method and Integer wrapper class. The valueOf() method is similar to the parseInt() method, but it also accepts an additional parameter that allows you to specify the base of the number that is being converted. Here is an example of how to do this:

String[] strArray = {"12", "15", "23"}; 

int[] intArray = new int[strArray.length]; 

for(int i=0 ; i<strArray.length ; i++) { 
    intArray[i] = Integer.valueOf(strArray[i], 10); 
} 

This method is useful when you need to convert a string that contains numbers in a different base than 10. For example, you could use this method to convert strings that contain hexadecimal numbers or binary numbers.

These are just two of the many methods that can be used to convert a string array into an int array in Java. Depending on your specific needs and requirements, there may be other methods that are more suitable for the task at hand.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.