Problem:
Attempts to convert an int array to a String using the toString(int[]) method but encountering an error when trying to invoke it on a new String object.
Code:
<code class="java">int[] array = new int[lnr.getLineNumber() + 1]; int i = 0; System.out.println(array.toString()); System.out.println(new String().toString(array)); // Error</code>
Error:
The method toString() is not applicable for arguments of type int[].
Solution:
The desired conversion can be achieved by utilizing the static Arrays.toString(int[]) method from the java.util package. Here's the modified code:
<code class="java">import java.util.Arrays; int[] array = new int[lnr.getLineNumber() + 1]; int i = 0; System.out.println(Arrays.toString(array));</code>
Description of Arrays.toString(int[]):
This method returns a string representation of an int array. The string comprises a list of array elements enclosed in square brackets. Adjacent elements are separated by commas followed by spaces.
Example Output:
The sample code with the corrected method invocation should produce an output along the lines of:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The above is the detailed content of How to Convert an Integer Array to a String in Java?. For more information, please follow other related articles on the PHP Chinese website!