I took an output.It's "[I@1ba4806
".What's the reason of it in Java?
out
static field in System
class is instance of PrintStream
and there is no println(int[])
method in PrintStream
class which would iterate for you over all elements in passed array and print them, but there is println(Object o)
which tries to convert passed object o
into as String which will be then printed.
To do that this method uses String.valueOf(o)
method which in case of o
being null will return "null" String, or in case where o
is not null (like in your example) it will return result of toString()
method invoked from passed object. So System.out.println(a);
prints result of a.toString()
.
Now why does array have would have toString()
method? Well it was inherited from Object
class (because all arrays extend Object). Also arrays do not override this method and they leave it in a way it was implemented in Object
class, so its code looks like
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
which as you see returns TypeName@hexadecimalHash
. One dimensional array of integers is represented as [I
where number of [
determines number of dimensions, and I
represents int
type.
If you would like to print content of array, you would either have to iterate over all elements and print them
for (int i = 0; int < array.lenght; i++){
System.out.println(array[i]);
}
or
for (int element : array){
System.out.println(element);
}
OR you can use Arrays.toString(int[])
method, which will do this for you and will generate string in form [1, 2, 3, ....]
so all you would need to do is print it like
System.out.println(Arrays.toString(a));