Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to declare an array in-line?

Tags:

java

arrays

Let's say I have a method m() that takes an array of Strings as an argument. Is there a way I can just declare this array in-line when I make the call? i.e. Instead of:

String[] strs = {"blah", "hey", "yo"}; m(strs); 

Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?

like image 503
DivideByHero Avatar asked Jul 20 '09 14:07

DivideByHero


People also ask

How do I write an array in one line?

String[] strs = {"blah", "hey", "yo"}; m(strs);

How do you initialize an array in one line in Java?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.

How do you properly declare an array?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

How do you correctly declare an array in Java?

When you declare a Java array variable you only declare the variable (reference) to the array itself. The declaration does not actually create an array. You create an array like this: int[] intArray; intArray = new int[10];


1 Answers

m(new String[]{"blah", "hey", "yo"}); 
like image 63
Draemon Avatar answered Oct 16 '22 07:10

Draemon