14

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

2
  • 15
    For questions as simple as this, you're probably best off just trying first, and then posting if you get stuck. Commented Oct 5, 2010 at 19:53
  • Welcome to stackoverflow..You might need to first refer to the most basic tutorials flooded out there on net and then try first before even expecting any help on SO Commented May 30, 2018 at 16:58

5 Answers 5

30

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

Sign up to request clarification or add additional context in comments.

Comments

6

Yes.

/** Returns a String array of length 5 */
public String[] createStringArray() {
    return new String[5];
}

Comments

6

Yes:

String[] dummyMethod()
{
    String[] s = new String[2];
    s[0] = "hello";
    s[1] = "world";
    return s;
}

1 Comment

The other obvious choice would have been "foo" + "bar", but then I see you managed to have a foo in your answer as well :)
1

yes.

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

Do you have a more specific need?

Comments

1

Sure

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.