Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to return a String array

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

like image 382
Luron Avatar asked Oct 05 '10 19:10

Luron


3 Answers

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

like image 144
Mark Byers Avatar answered Oct 20 '22 20:10

Mark Byers


Yes.

/** Returns a String array of length 5 */
public String[] createStringArray() {
    return new String[5];
}
like image 35
Mark Peters Avatar answered Oct 20 '22 19:10

Mark Peters


Yes:

String[] dummyMethod()
{
    String[] s = new String[2];
    s[0] = "hello";
    s[1] = "world";
    return s;
}
like image 6
Grodriguez Avatar answered Oct 20 '22 21:10

Grodriguez