0

I've come across what appears to be an interesting bug...

For one of my classes, I need to write a program that simulates the old "x students going down a hallway closing lockers every x interval" scenario. However, an interesting twist is that the question requires there to be an equal number of students and lockers up to 100. So I decided to use an array, where the user input a number - which is then used to set up the array size, for-loop conditions, etc. etc... you get the picture, right?

Anyway, my code compiles, but when run it puts out something like:

[I@36ae2282

Someone (in another thread/question/whatever-you-call-it) stated that this is the physical location of the array in the system memory, and to get the actual numbers from the array the .getNums() method would be required. My problem is: the .getNums() method doesn't seem to exist in Java (perhaps it's part of another language?), so what is the next best alternative or solution?

JGeorge
  • 23
  • 2
  • Could you post the code where you 1) declare the array 2) initialise the array 3) print the array? – 11684 Feb 27 '13 at 20:42

2 Answers2

4

You're printing out the int array, and that's a traditional array's .toString() representation. You may want to use Arrays.toString() for nicer looking output instead.

Makoto
  • 104,088
  • 27
  • 192
  • 230
1

To print the content of an array either iterate over each element in the array:

int[] array = new int[10];

for(int s : array) System.out.println(s);
// or
for(int i = 0; i < array.length; i++) System.out.println(array[i]);

or use Arrays.toString():

int[] array = new int[10];
System.out.println(Arrays.toString(array));

which will print something like:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Anyway, my code compiles, but when run it puts out something like:

[I@36ae2282

I assume you are trying to print the array like this:

int[] array = new int[10];
System.out.println(array);

array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():

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

So the output would be something like:

[I@756a7c99

where [ represnts the depth of the array, and I refers to int. 756a7c99 is the value returned from hashCode() as a hex number.

Read also Class.getName() JavaDoc.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417