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);
}
}
Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ( [ and ] ) attached to the end. When calling the function, simply pass the address of the array (that is, the array's name) to the called function.
Array literals An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference. It's notable that the former form is often regarded as ill-formed since the dimension is lost.
Advantages of Passing Arrays to FunctionsPassing similar elements as an array takes less time than passing each element to a function as we are only passing the base address of the array to the function, and other elements can be accessed easily as an array is a contiguous memory block of the same data types.
{"foo"}
doens't tell Java anything about what type of array you are trying to create...
Instead, try something like...
takesStringArray(new String[] {"foo"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With