Reputation: 79
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.
Upvotes: 0
Views: 101
Reputation: 608
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"});
Upvotes: 0
Reputation: 497
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){
}
}
Upvotes: 0
Reputation: 2403
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);
Upvotes: 0
Reputation: 522741
Just intialize an array of strings and pass it:
method(new String[]{"This", "is", "an", "array"});
Upvotes: 2
Reputation: 11483
Use varargs:
public void method(String... values) {
//...
}
method("Hello", "World");
Upvotes: 1