Java: passing println array

The following contrived example I just made 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 gives out trash. Since a is passed by reference, I assume that println gets the memory address of a and threatens it as a string. Am I right here? Can you clarify what exactly is happening? Thank you (note: I'm not interested in how to print an array. I know that.)

+2
java arrays
source share
3 answers

An array is considered an object, so the original result of Object#toString() will be used as a string representation. See also this excerpt from Javadoc (click the link):

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

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

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

 System.out.println(Arrays.toString(a)); 
+5
source share

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

0
source share

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

0
source share

All Articles