I executed the below mentioned code, when I got a strange output. Can anyone please explain why I am getting this output ?
Code:
public class Bar {
static void foo( int... x ) {
System.out.println(x);
}
static void foo2( float... x ) {
System.out.println(x);
}
public static void main(String args[])
{
Bar.foo(3,3,3,0);
Bar.foo2(3,3,3,1);
Bar.foo(0);
}
}
Output
[I@7a67f797
[F@3fb01949
[I@424c2849
Why are we getting the "[I@"
/"[F@"
prefixes and the 8 alphanumeric characters to follow, are they memory address ?
Java arrays have a toString()
method that simply display the type of the array ([I
), followed by an @
, followed by the hash code of the array (7a67f797
). This value is almost meaningless. And toString()
is the method called on every object passed to System.out.println()
.
If you want to see the contents of the array, then use java.util.Arrays.toString(array)
.
float...
is syntactic sugar for float[]
, so
System.out.println(x);
...is trying to output an array. So you're getting the default toString
behavior of objects, rather than the values in the array.
To output the array, either loop through it, or use something like Arrays.toString
:
System.out.println(Arrays.toString(x));
...and the 8 alphanumeric characters to follow, are they memory address ?
No, they're just the object's hash code (this is covered in the first link above).
Use this to see values in array.
System.out.println(x[0]);
System.out.println(x[1]);
....
System.out.println(x[3]);
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