I have a string array with four elements in it that I defined. How come when I type System.out.println(name of Array)
, it doesn't output the elements? But instead gives me a weird output.
Here's my code...
public class GeniusTrial {
public static void main(String[]args) {
String [] genius = {"Einstein, ", "Newton, ", "Copernicus, ", "Kepler."};
System.out.print(genius);
}
}
Here is the output that I got:
[Ljava.lang.String;@3e25a5
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 classObject
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.
Use the Arrays class to expand the array for you:
System.out.println(Arrays.toString(genius));
will give you
[Einstein,,Newton,,Copernicus,,Kepler.]
The double commas are because you included them in your array; remove them and you'll get a nice comma-separated list.
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