Stumbler
Stumbler

Reputation: 2146

Array reference explanation

For the code

int []arr = new int[4];
System.out.println(arr);

The output looks something like

[I@54640b25

What exactly is the compiler printing out? The memory address of arr? Unlike C, Java does not seem to equate the array name (in isolation) with the first position of the array.

Upvotes: 1

Views: 79

Answers (2)

Salah
Salah

Reputation: 8657

Use the following in order to print the value of array:

Arrays.toString(arr);

Using System.out.println(arr) directory will print use the default toString method which returns:

object.getClass().getName() + "@" + Integer.toHexString(object.hashCode())

Upvotes: 3

Maroun
Maroun

Reputation: 96016

In Java, each object has toString() method, and arrays are objects. The default is displaying the class name representation, then adding "@" and then the hashcode:

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

Try to print the following line and you should get the same output:

int[] arr = new int[5]; 
System.out.println(arr.getClass().getName() + "@" + Integer.toHexString(arr.hashCode()));

Upvotes: 6

Related Questions