Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java arrays printing out weird numbers and text [duplicate]

I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.

Ok, I'll go right to it.

Here's my code:

int[] arr;
arr = new int[5];

arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;

System.out.println(arr);

This compiles and works fine. It's just the output from CMD that I'm dizzy about.

This is the output: [I@3e25a5.

I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?

like image 822
Racket Avatar asked Dec 18 '10 19:12

Racket


4 Answers

Every object has a toString() method, and the default method is to display the object's class name representation, then @ followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:

System.out.println(java.util.Arrays.toString(arr));

Or, you can loop through the array with a for loop as others have posted in this thread.

like image 119
Hovercraft Full Of Eels Avatar answered Nov 02 '22 20:11

Hovercraft Full Of Eels


System.out.println(Arrays.toString(arr));

The current output is classtype@hashcode.

Incase you need to print arrays with more than one dimension use:

Arrays.deepToString(arr);

Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype@hashcode

like image 45
Emil Avatar answered Nov 02 '22 19:11

Emil


It's the default string representation of array (the weird text).

You'll just have to loop through it:

for(int i : arr){
System.out.println(i);
}
like image 5
Goran Jovic Avatar answered Nov 02 '22 19:11

Goran Jovic


To print the values use.

for(int i=0; i<arr.length; i++)
   System.out.println(arr[i]);
like image 5
Enrique Avatar answered Nov 02 '22 20:11

Enrique