15

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
Ryan Kohn
  • 13,079
  • 14
  • 56
  • 81
rahme24
  • 161
  • 1
  • 3
  • 6
  • 3
    @Anthony, that's not very helpful to a new user...you were curt and you didn't give him the best answer. Now use what you've learned about the `Arrays` class :) – Paul Dec 07 '11 at 04:16
  • 4
    @Paul, he's doing homework. Presumably his instructor has taught him about loops. He should use what he has learned in order to complete his assignment. Shortcuts might be beneficial, but learning the basics is what he should be doing. – Anthony Pegram Dec 07 '11 at 04:18
  • @Anthony...shortcuts? It's part of the core Java library - knowing the API is not a shortcut. I wouldn't presume to know what his instructor has taught him...and it may not even be homework. Perhaps he's learning on his own. – Paul Dec 07 '11 at 04:21
  • 2
    @Paul, he labelled it homework. If he's applying that tag a bit more liberally than normal, so be it. Loops are fundamentals. Abstracting away loops are next steps. I'm assuming at this point in his learning, he's still learning the fundamentals. If you feel differently, fine. – Anthony Pegram Dec 07 '11 at 04:22
  • 1
    http://stackoverflow.com/questions/3319510/java-language-design-with-tostring , http://stackoverflow.com/questions/409784/simplest-way-to-print-an-array-in-java , http://stackoverflow.com/questions/4297361/java-passing-an-array-to-println –  Dec 07 '11 at 04:40
  • Take a look at Arrays.toString(Object[]) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(java.lang.Object[]) – keuleJ Aug 16 '13 at 06:42

6 Answers6

24

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 Strings 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.

Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • Let's say I want a different formatting. What options do I have? – Anthony Pegram Dec 07 '11 at 04:34
  • @AnthonyPegram - Then of course you would need to roll your own implementation. Do you recommend I edit my answer to mention that? – Paul Bellora Dec 07 '11 at 04:41
  • I think it would be worth mentioning the default format to expect if using the mentioned approach, keeping in mind that the user is learning, and what to do if that format isn't useful, which may simply lead to the second part of your answer. – Anthony Pegram Dec 07 '11 at 04:43
  • @AnthonyPegram - Understood, let me improve it in that respect. – Paul Bellora Dec 07 '11 at 04:48
  • @AnthonyPegram - Let me know if you see anything that could be further improved upon. As an aside, I understand your point of view in the comments above and appreciate the need to make posts like this educational instead of spoon feeding. Thanks for prodding a better answer out of me :) – Paul Bellora Dec 07 '11 at 05:30
14

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.

Paul
  • 19,704
  • 14
  • 78
  • 96
  • Yes, generally the better way, but not often "homework" compatible ;-) Up-vote for mentioning the double-comma. –  Dec 07 '11 at 04:29
  • Let's say I want a different formatting. What options do I have? – Anthony Pegram Dec 07 '11 at 04:33
  • @AnthonyPegram, if it was me I'd either use the [`join`](http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html#join%28java.lang.Object[],%20char%29) method of [Commons Lang](http://commons.apache.org/lang/) or use a `StringBuilder` in a loop, depending on if Commons Lang was already in use in the project I was working on...and the formatting requirements of course. – Paul Dec 07 '11 at 04:45
3

You need a loop:

for(String gen : genius)
{
    System.out.print(gen);
}

Every object has a toString() method which is what you are seeing, the string array's toString.

Paul
  • 19,704
  • 14
  • 78
  • 96
Joe
  • 80,724
  • 18
  • 127
  • 145
3

So in your for loop is going to be like:

for(i=0;i<genius.length;i++) {
 system.out.print(genius[i]);
}

So I will explain what this does. A for loop is structured like this:

for(original value; condition for the variable to go through the for loop; what to do to variable at end of for loop)

So you start with i=0 and that fills the condition: i is less than genius.length (genius.length gives the length of the array which would be 4 in this case). So it would go through loop and print genius[i] (which would be genius[0]) because i=0. Then it would add one to i (i++).

It would go through loop again because i=1 fills condition i is less than genius.length..... and so on...

It would go to i=4 and stop. You may think, what about genius[4]?? Well the array data is named like this 1st= arrayname[0], 2nd = arrayname[1]..... So the fourth will be genius[3]. So when i=4 it stops and all are printed.

You can change the format of how their printed by replacing with system.out.print(genius[i] + ", "); This will put a comma and space after each one.

Hope it helps, good luck.

Antoine Dahan
  • 574
  • 2
  • 9
  • 23
  • 1
    +1 very nicely explained, tho', I don't think he paid too much attention in class (: –  Dec 07 '11 at 04:45
2

Use enhanced for loop to iterate, like this

for(String str:genius){
    System.out.println(str)
}
Selvakumar Ponnusamy
  • 5,363
  • 7
  • 40
  • 78
1

You need to iterate over your array (with a for loop for example) and print each value separately.

If you try to print an array it will print information about the object that you will not find really interesting.

talnicolas
  • 13,885
  • 7
  • 36
  • 56