Reputation: 3023
How do I pass a array without making it a seperate variable? For example I know this works:
class Test{
public static void main(String[] args){
String[] arbitraryStrings={"foo"};
takesStringArray(arbitraryStrings);
}
public static void takesStringArray(String[] argument){
System.out.println(argument);
}
}
But I dont want to make the array a variable as it is only used here. Is there any way to do something like this:
class Test{
public static void main(String[] args){
takesStringArray({"foo"});
}
public static void takesStringArray(String[] argument){
System.out.println(argument);
}
}
Upvotes: 10
Views: 9271
Reputation: 3686
You can use varargs:
class Test {
public static void main(String[] args) {
takesStringArray("foo");
}
public static void takesStringArray(String... argument) {
System.out.println(argument);
}
}
Upvotes: 0
Reputation:
u may try VarArgs:
class Test{
public static void main(String[] args){
takesStringArray("foo", "bar");
}
public static void takesStringArray(String... argument){
System.out.println(argument);
}
}
Upvotes: 0
Reputation: 117
class Test {
public static void main(String[] args) {
takesStringArray(new String[]{"foo"});
}
public static void takesStringArray(String[] argument) {
System.out.println(argument);
}
}
Upvotes: 2
Reputation: 347314
{"foo"}
doens't tell Java anything about what type of array you are trying to create...
Instead, try something like...
takesStringArray(new String[] {"foo"});
Upvotes: 26
Reputation: 122006
You are able to create an array with new
, and without A new variable
The correct syntax you are expecting is,
takesStringArray(new String[]{"foo"});
Seems, you are just started with arrays
.There are many other syntax's to declare an array
.
Upvotes: 2
Reputation: 5531
use in-line
array declaration
try
takesStringArray(new String[]{"foo"});
Upvotes: 1