8

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,486
  • 2
  • 28
  • 49
  • 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

25

{"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,951
  • 4
  • 25
  • 43
MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
2

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
  • 118,038
  • 37
  • 189
  • 297
1
class Test {
    public static void main(String[] args) {
        takesStringArray(new String[]{"foo"});
    }

    public static void takesStringArray(String[] argument) {
        System.out.println(argument);
    }
}
Cristian Lupascu
  • 37,084
  • 15
  • 94
  • 135
Jixi
  • 107
  • 1
  • 13
0

use in-line array declaration

try

takesStringArray(new String[]{"foo"});
upog
  • 4,565
  • 7
  • 35
  • 70
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
  • 24,336
  • 15
  • 57
  • 93
Korniltsev Anatoly
  • 3,635
  • 2
  • 25
  • 36