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?
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.
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
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);
}
To print the values use.
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With