Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arrays as Parameters

Tags:

java

arrays

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.

like image 804
Anonymous Person Avatar asked Oct 29 '11 05:10

Anonymous Person


People also ask

Can arrays be passed as parameters in 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.

Can you use an array as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

When you pass an array as a parameter?

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);

Can we pass an array in function as a parameter?

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.


2 Answers

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.

like image 22
BalusC Avatar answered Oct 12 '22 02:10

BalusC


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"});
like image 193
nfechner Avatar answered Oct 12 '22 01:10

nfechner