dot
dot

Reputation: 109

Printing an array without stating which one leads leads to a String of random code

While I was working on a project of mine, I tried to print out an integer from an array using the following code:

Random dice = new Random();
int wolfhealth[] = new int[]{dice.nextInt(15)+9};
System.out.println(wolfhealth);  

I accidentally forgot to state which integer I wanted to print out from the array of integers which lead to it printing out this line of code:

[I@75b84c92

I have already fixed the issue by changing the 3rd line into

System.out.println(wolfhealth[0]);

My question is, what does this line of code - [I@75b84c92 mean exactly? Is it some kind of unique identifier or ID for the array?

Upvotes: 5

Views: 322

Answers (3)

Jim Garrison
Jim Garrison

Reputation: 86774

That is output from the default toString() implementation from Object, as "overridden" for array objects.

The output encodes the type and memory address:

[ I @75b84c92
▲ ▲  ▲
│ │  └─── hash code
│ └─── of integer
└─── array

Upvotes: 7

Aniruddh Dikhit
Aniruddh Dikhit

Reputation: 682

Taking an array arr for example all three will print the same result

    int[] arr  = new int[20];

    System.out.println(arr);
    System.out.println(arr.toString());
    System.out.println(String.format("%s@%x", arr.getClass(), arr.hashCode())); 

Essentially when System.out.println is called every object's toStriing method is called so the effect of calling arr.toString also yields the same thing as what printing arr gives. The last statement is just demonstrating what's being done inside toString of the array class.

Upvotes: 2

Nikolay Tomitov
Nikolay Tomitov

Reputation: 947

Arrays in java are referent types. That means that you actually store a reference(an address) in stack memory to some other memory in heap. The first 2 symbols mean that this is an array of ints ([I) and latter mean that it located in some address in heap space (@ 75b84c92). Hope this helps to understand it. You may also see a contents of an array (mainly for debug purposes) using Arrays.toString(a)

Upvotes: 2

Related Questions