Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int array to String with toString method in Java [duplicate]

I am using trying to use the toString(int[]) method, but I think I am doing it wrong:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])

My code:

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

System.out.println(array.toString());

The output is:

[I@23fc4bec

Also I tried printing like this, but:

System.out.println(new String().toString(array));  // **error on next line**
The method toString() in the type String is not applicable for the arguments (int[])

I took this code out of bigger and more complex code, but I can add it if needed. But this should give general information.

I am looking for output, like in Oracle's documentation:

The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).

like image 653
Jaanus Avatar asked Sep 28 '22 20:09

Jaanus


People also ask

Can you convert an array to string?

To convert a JavaScript array into a string, you can use the built-in Array method called toString .

Can Java convert integers to strings automatically?

Integer to String conversion in Java There are many ways to convert an Integer to String in Java e.g. by using Integer. toString(int) or by using String. valueOf(int), or by using new Integer(int). toString(), or by using String.


1 Answers

What you want is the Arrays.toString(int[]) method:

import java.util.Arrays;

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

..      

System.out.println(Arrays.toString(array));

There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:

public static String toString(int[] a)

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.

like image 314
Sbodd Avatar answered Oct 18 '22 23:10

Sbodd