0

Possible Duplicate:
Simplest way to print an array in Java

How do I even print arrays? I'm trying to experiment on some methods and all I keep on getting are garbage values. I tried to import the Arrays library - still didn't work.

    int []x = {1, 2, 3, 4, 5};
    int []y;
    y = x.clone();
    System.out.println(x);
    System.out.println(y);
Community
  • 1
  • 1
nutellafella
  • 135
  • 1
  • 4
  • 17
  • 5
    possible duplicate of [Simplest way to print an array in Java](http://stackoverflow.com/questions/409784/simplest-way-to-print-an-array-in-java), http://stackoverflow.com/questions/4297361, http://stackoverflow.com/questions/8410294, ... – Tomasz Nurkiewicz Jul 09 '12 at 17:21

2 Answers2

6

Isn't garbage. Is the default implementation of toString for this class.

The easiest way to get the elements printed on a readable format is:

String printed = Arrays.toString(x);

Documentation for Arrays.toString(int[])

The same approach can be used to print out array of primitives and Objects.

Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
5

It is not a garbage value; it is the toString() implementation of int[],

If you want to print the contents of array

public void printArray(int[] arrray){
 for(int number: array){
   System.out.println(number);
 }
}

See Also

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    Yup - and see [Arrays.toString()](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#toString%28int[]%29) and its like for potentially nicer ways to print them. – Rob I Jul 09 '12 at 17:22