-1

How can I return a string[] from a method:

public String[] demo
{
  String[] xs = new String {"a","b","c","d"};
  String[] ret = new String[4];
  ret[0]=xs[0];
  ret[1]=xs[1];
  ret[2]=xs[2];
  ret[3]=xs[3];

  retrun ret;
}

Is this right, because I tried it and it didn't work. How can I print this returned string array in main method.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
Hitman
  • 87
  • 1
  • 1
  • 6

2 Answers2

9

Your code won't compile. It suffers from many problems (including syntax problems).

You have syntax errors - retrun should be return.

After demo you should have parenthesis (empty if you don't need parameters)

Plus, String[] xs = new String {"a","b","c","d"};

should be:

String[] xs = new String[] {"a","b","c","d"};

Your code should look something like this:

public String[] demo()  //Added ()
{
     String[] xs = new String[] {"a","b","c","d"}; //added []
     String[] ret = new String[4];
     ret[0]=xs[0];
     ret[1]=xs[1];
     ret[2]=xs[2];
     ret[3]=xs[3];
     return ret;
}

Put it together:

public static void main(String args[]) 
{
    String[] res = demo();
    for(String str : res)
        System.out.println(str);  //Will print the strings in the array that
}                                 //was returned from the method demo()


public static String[] demo() //for the sake of example, I made it static.
{
     String[] xs = new String[] {"a","b","c","d"};
     String[] ret = new String[4];
     ret[0]=xs[0];
     ret[1]=xs[1];
     ret[2]=xs[2];
     ret[3]=xs[3];
     return ret;
 }
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

try this:

//... in main
String [] strArr = demo();
for ( int i = 0; i < strArr.length; i++) {
    System.out.println(strArr[i]);
}

//... demo method
public static String[] demo()
{
    String[] xs = new String [] {"a","b","c","d"};
    return xs;
}
duffy356
  • 3,678
  • 3
  • 32
  • 47