views:

116

answers:

5

Is it possible to make a method that returns a string [ ] in java????

+8  A: 

Yes, but in Java the type is String[], not string[]. The case is important.

For example a method could look something like this:

public String[] foo() {
    // ...
}

Here is a complete example:

public class Program
{
    public static void main(String[] args) {
        Program program = new Program();
        String[] greeting = program.getGreeting();
        for (String word: greeting) {
            System.out.println(word);
        }
    }

    public String[] getGreeting() {
        return new String[] { "hello", "world" };
    }
}

Result:

hello
world

ideone

Mark Byers
thats what i meant.
Luron
+6  A: 

Yes.

/** Returns a String array of length 5 */
public String[] createStringArray() {
    return new String[5];
}
Mark Peters
+3  A: 

Yes:

String[] dummyMethod()
{
    String[] s = new String[2];
    s[0] = "hello";
    s[1] = "world";
    return s;
}
Grodriguez
+1 heh nearly identical to my example!
Mark Byers
The other obvious choice would have been "foo" + "bar", but then I see you managed to have a foo in your answer as well :)
Grodriguez
+1  A: 

yes.

public String[] returnStringArray()
{
    return new String[] { "a", "b", "c" };
}

Do you have a more specific need?

John Gardner
A: 

Sure

public String [] getSomeStrings() {
    return new String [] { "Hello", "World" };
}
superfell