Printing array elements with toString()

Printing array elements with toString()


Arrays.toString() method makes it easier to print the elements of an array, forgetting the tedious iteration with for loops.

Following is the method signature

  • static String toString(int array1[]): Returns the array in string form useful to be displayed in a text field. This display the array elements comma-separated and placed within square brackets, "[]". Returns null if the array refers a null. This method eliminates the for loop to print the elements. Comes into existence with JDK 1.5.
Following program on Printing array elements with toString() prints the elements of an array with the for loop and also with toString().


Printing array elements with toString()
Output screenshot on Printing array elements with toString()

Printing the string array object languages prints some value (observe the screenshot) not useful for us in programming. That is, the object languages does not print the elements.

The elements of languages are printed using JDK 1.5 enhanced for loop, commonly known as foreach loop.

To overcome the writing of for loop, the Arrays class comes with toString() method. The toString() method returns a string that contains all the elements list. Here after, in the all the Array examples, toString() method is used to print the array elements.

Actually there is a toString() method in Object class which converts any Java object into string form. The toString() method returns a string. toString() method of Object class is equivalent to valueOf() method of String class.

The Arrays class from java.util package does not have copy() method to copy the elements of one array to another as arraycopy() method already exists with general arrays.

Leave a Reply

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