0

I am creating a String array and using System.out.println to print the values in the array. All good and works as expected, returning [South Africa, England] but the code won't compile unless I include a return statement, but the return statement just dumps out a load of garbage "[Ljava.lang.String;@85bdf6". Is there any way I can either combine the System.out.println and return statements so they do the same thing, and I just have [South Africa, England] appearing?

   public String[] teamsToProgress()
  { 
    Arrays.sort(teams);
    String[] teamsToProgress;
    teamsToProgress = new String[2];
    String team1 = teams[0].getName();
    String team2 = teams[1].getName();
    teamsToProgress[0] = team1;
    teamsToProgress[1] = team2;
    System.out.println(Arrays.toString(teamsToProgress));
    return teamsToProgress;
  }
user435346
  • 5
  • 1
  • 5
  • 4
    `the code won't compile unless I include a return statement` - that's usually the case when your method has a return type other than void. – Eran May 05 '15 at 18:33
  • 1
    Do you want the method to return the array to its caller or just print the array? – Eran May 05 '15 at 18:34

2 Answers2

2

That's because you have String[] as a return type. Change it to void and it will compile just fine. You can read here what that 'garbage' [Ljava.lang.String;@85bdf6 means.

Community
  • 1
  • 1
Jyr
  • 711
  • 5
  • 16
1

but the return statement just dumps out a load of garbage "[Ljava.lang.String;@85bdf6"

That's not the return statement, thats what you do with the return value. Most probably you have used

System.out.println(teamsToProgress());

instead you should do what you have done in teamsToProgress() already.

System.out.println(Arrays.toString(teamsToProgress()));

In the first case you print what's returned by the toString() method of the array (some type information and the hash code), in the second case you print the content of the array.

Generally it's a good idea to either remove the System.out.println(...) from the teamsToProgress() and print the return value instead - or make the return value void and in this case find a better name for the method like void printTeamsToProgress(), so the intention of the method becomes clearer.

tomse
  • 501
  • 2
  • 7