Can you pass a new array as a method, and still have data in that array?
For example, I have this method: foo(String[])
, and i want to call it like thisfoo(new String[] s = {"String1", "String2"})
. But that's not valid Java.
To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);
Just like normal variables, Arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
This is a "valid Java way" (as in, it compiles and does what you want):
foo(new String[] {"String1", "String2"});
If you have the opportunity to change this method, then you can also consider to change the method to take a varargs argument:
public void foo(String... strings) {
// ...
}
Then you can use it as follows without the need to explicitly create an array:
foo("String1", "String2");
The following is then also valid:
foo("String1");
and
foo("String1", "String2", "String3");
and even more.
If you want to pass only the value and don't need the variable s
anymore, do it like this:
foo(new String[] {"String1", "String2"});
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