I am new to array concept there is something i cant understand that is i have read somewhere that when we intialize an array like int[] a = {1,2,3,4} ;
then a actually contain the address of memory location of the the first element of that array I havent statrted oop yet but as i know when toString method is used on reference variables it converts the value of an object that the reference variable contains its address to string but why when use
System.out.print(Arrays.toString(a));
the whole array is printed rather than just first element of array a ? because array a contains the address of first element only
Advertisement
Answer
The array was printed because you called Arrays.toString(int[] a)
method
Which is implemented by JAVA API
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(int[])
/** * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(int)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is * <tt>null</tt>. * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(int[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } }
For more clarity related to arrays memory representations,
Kindly check the below diagram: