9

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.

5 Answers 5

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How to get the vaue then?
4

If you're trying to make a local variable s and keep it around, no, you can't declare a variable within a method call. You have to declare it first outside of the call:

String[] s = {"String1", "String2"};
foo(s);

You could initialize s within the call, but I don't see any reason to do so, plus it looks really bad:

String[] s;
foo(s = new String[] {"String1", "String2"});

Comments

3

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

Comments

0

You can't declare a variable, but you can pass an array:

foo(new String[] { "String1", "String2" });

If you want to reference the same array later, then you need to declare it before the call.

Comments

0

You could just do foo(new String []{"String1","String2"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.