7

How do I pass a array without making it a seperate variable? For example I know this works:

class Test{
    public static void main(String[] args){
        String[] arbitraryStrings={"foo"};
        takesStringArray(arbitraryStrings);
    }
    public static void takesStringArray(String[] argument){
        System.out.println(argument);
    }
}

But I dont want to make the array a variable as it is only used here. Is there any way to do something like this:

class Test{
    public static void main(String[] args){
        takesStringArray({"foo"});
    }
    public static void takesStringArray(String[] argument){
        System.out.println(argument);
    }
}
Others
  • 2,316
  • 1
  • 25
  • 48
  • 2
    possible duplicate of [Passing directly an array initializer to a method parameter doesn't work](http://stackoverflow.com/questions/12805535/passing-directly-an-array-initializer-to-a-method-parameter-doesnt-work) – Rohit Jain Oct 23 '13 at 05:40
  • Consider taking a look at Groovy: http://groovy.codehaus.org/. In Groovy, you can just define list literals anywhere you like. it's sweet! – Ian Durkan Jan 07 '14 at 22:36

6 Answers6

19

{"foo"} doens't tell Java anything about what type of array you are trying to create...

Instead, try something like...

takesStringArray(new String[] {"foo"});
Jonny Henly
  • 3,725
  • 4
  • 23
  • 41
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
1

You are able to create an array with new, and without A new variable

The correct syntax you are expecting is,

  takesStringArray(new String[]{"foo"});

Seems, you are just started with arrays.There are many other syntax's to declare an array.

Community
  • 1
  • 1
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
0

use in-line array declaration

try

takesStringArray(new String[]{"foo"});
upog
  • 4,309
  • 6
  • 30
  • 59
0
class Test {
    public static void main(String[] args) {
        takesStringArray(new String[]{"foo"});
    }

    public static void takesStringArray(String[] argument) {
        System.out.println(argument);
    }
}
Cristian Lupascu
  • 34,894
  • 15
  • 87
  • 127
Jixi
  • 97
  • 1
  • 13
0

u may try VarArgs:

class Test{
    public static void main(String[] args){
        takesStringArray("foo", "bar");
    }
    public static void takesStringArray(String... argument){
        System.out.println(argument);
    }
}
0

You can use varargs:

class Test {
    public static void main(String[] args) {
        takesStringArray("foo");
    }

    public static void takesStringArray(String... argument) {
        System.out.println(argument);
    }  
}
Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
Korniltsev Anatoly
  • 3,595
  • 2
  • 24
  • 33