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?
String[] strs = {"blah", "hey", "yo"}; m(strs);
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.
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};
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];
m(new String[]{"blah", "hey", "yo"});
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