Example CodeJavaTips

String Utility Methods: Converting int[] to String

1 Mins read
java array tostring, convert java array to string, convert array to string, toString() method for array, array utility method convert to string, print array as string, string from array, convert array into string
Java has many in built operations supported by String class. There are few functions which I observed commonly used and may be helpful to keep handy as StringUtil class with static methods. I have already posted a toString() method for an Object array. Below is a utility method which can be used to display the array of int in String format, just like we can display Collections. The Java collections framework has toString method implemented for all its collections, but if we are utilizing a int array instead then converting the whole array to String has to be done a separate method along with writing toString() method for class. Below method can be called to convert the array to String representation same as collections. This will return a string with values separated by comma.  
 
/**

* This method iterates over the array of int data to comma separated String

*

* As an example : <blockquote>

*

* <pre>

* int []lmn = {1,2,3,4,5};

* The output achieved is : 1,2,3,4,5

* </pre>

*

* </blockquote>

*

* @param intArray

* The int array

* @return Concatenated string

*/

public static String toString(int[] intArray) {

String separator =

“,”;

StringBuilder sb =

new StringBuilder(“”);

if (intArray != null && intArray.length > 0) {

for (int i = 0; i < intArray.length; i++) {

sb.append(intArray[i]);

if (i < (intArray.length – 1)) {

sb.append(separator);

}

}

}

return sb.toString();

}

Leave a Reply

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