2

The following is a contrived example I just made up to help me understand the inner workings of java.

public class Main {

    public static void main(String[] args) {
        int[] a;
        a = new int[12];
        System.out.println(a);


    }
}

This prints out some garbage. Since a is passed by reference, I presume println gets the memory address of a, and threats it as a string. I'am right here? Can you elaborate what happens exactly? Thanks. (note: I am not interested in how to print an array. I know that.)

noname
  • 23
  • 3

3 Answers3

5

An array is treated as an object, so the default outcome of Object#toString() will be used as string representation. See also this extract of the Javadoc (click the link):

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

    getClass().getName() + '@' + Integer.toHexString(hashCode())

To achieve what you want, rather use Arrays#toString().

System.out.println(Arrays.toString(a));
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Yes, it is printing the memory address. See the Q&A section here: http://www.cs.princeton.edu/introcs/14array/ Use Arrays.toString(a) to convert the array a into a String which can be printed if you want to output the array's contents.

moinudin
  • 134,091
  • 45
  • 190
  • 216
0

println() calls the toString() method of whatever you pass to it. In the case of an array, this results in some hashcode representing the array object.

froadie
  • 79,995
  • 75
  • 166
  • 235