0

So, my question is you know how we are able to pass String as argument to a method by just doing method("This","are","Strings");

How can you do this with an array of String when the method is supposed to hold a array. I know that you cant do this method({"This","is","an","array"}); Is there any way of doing something similar? And thank you in advance.

5 Answers 5

2

Just intialize an array of strings and pass it:

method(new String[]{"This", "is", "an", "array"});
Sign up to request clarification or add additional context in comments.

Comments

1

Use varargs:

public void method(String... values) {
    //...
}

method("Hello", "World");

3 Comments

Or, if the method must take an array, method(new String[] {"Hello", "World"});
Well, varargs is an array. If it must be an array literal then just new String[] {}, but that'd be no different than having the array initialized before.
He might be unable to change method's argument list though.
0

You can send array of strings like below.

method(String[] arr){}

and call that method with string array as argument.

String array = new String[]{"value1","value2"};
method(array);

Comments

0

You can try this can take an optional list of strings and also you need to make it the last argument and mention other before.

private void method(String... values){
        for (String s : values){

        }
    }

Comments

0

You can do it like this.

public static void arrayString(String[] params) 
{
   System.out.println(Arrays.toString(params));
}

While calling call it as

arrayString(new String[]{"This","is","an","array"});

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.