Home > Java > javaTutorial > How to Convert an Integer Array to a String in Java?

How to Convert an Integer Array to a String in Java?

Linda Hamilton
Release: 2024-11-03 07:35:02
Original
1061 people have browsed it

How to Convert an Integer Array to a String in Java?

Converting an Int Array to a String Using toString

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>
Copy after login

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>
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template