The toString()
method of an array returns a String
describing the identity of the array rather than its contents. That's because arrays don't override Object.toString()
, whose documentation explains what you're seeing:
The toString
method for class Object
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
To get a String
representation of an array's contents, you can use Arrays.toString(Object[])
.
The String
returned by this method consists of each element's toString()
representation, in the order they appear in the array and enclosed in square brackets ("[]"
). Adjacent elements are separated by a comma and space (", "
).
For example, calling this method on your array would result in the following String
:
"[Einstein, , Newton, , Copernicus, , Kepler.]"
Note that the double commas and odd spacing are resulting because your array's element String
s already have punctuation and white space in them. Removing those:
String [] genius = {"Einstein", "Newton", "Copernicus", "Kepler"};
The method would then return this String
:
"[Einstein, Newton, Copernicus, Kepler]"
It's important to notice that using this method doesn't give you any control over the formatting of the resulting String
. It's nice for quickly checking the contents of an array, but is limited beyond that purpose. For example, what if you don't want those enclosing square brackets, or want to list each element line-by-line?
At this point you should start to see the value of implementing your own method to output the contents of your array in a way that's specific to your task. As others have suggested, practice this by using a for
loop and building the new resulting String
that you want to output.
You can find more information on for
loops in this Java Tutorials article. In general, the Java Tutorials are great reading for a beginner and should accompany your course well.