This question already has an answer here:
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 defaulttoString()
representation of anint
array. To print the data in the array, you can use:Or, you can loop through the array with a
for
loop as others have posted in this thread.It's the default string representation of array (the weird text).
You'll just have to loop through it:
BTW You can write
or even
or
To print the values use.
You printed the reference and not the values at the reference... One day it will all become clear with C.
Like this:
That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.
You should override it in your own objects if seeing the reference isn't sufficient.