Way2Java

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

Following program on Printing array elements with toString() prints the elements of an array with the for loop and also with toString().
import java.util.Arrays;
public class ArraysToString
{
  public static void main(String args[])
  {
    String languages[] = { "C", "C++", "Java", "Smalltalk" };  
    System.out.println(languages);

    System.out.print("With for loop: ");
    for(String str : languages)
    {
      System.out.print(str + " ");
    }
   
    System.out.print("\n\nWith toString(): ");
    String s1 = Arrays.toString(languages);
    System.out.print(s1);
  }
}



Output screenshot on Printing array elements with toString()
     String languages[] = { "C", "C++", "Java", "Smalltalk" };  
     System.out.println(languages);

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.

     for(String str : languages)
     {
       System.out.print(str + " ");
     }

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

     String s1 = Arrays.toString(languages);
     System.out.print(s1);

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.