37

In PHP you can do the following:

method(array("a", "b"));

Can you in Java initialize a String array as an argument in the method call, something like tihs:

method(new String[] = {"a", "b"});

Thanks!

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
aksamit
  • 2,325
  • 8
  • 28
  • 40

4 Answers4

80

Java has an equivalent construct:

import java.util.Arrays;

public class Foo {
   public void method(String[] myStrArray) {
      System.out.println(Arrays.toString(myStrArray));
   }

   public static void main(String[] args) {
      Foo foo = new Foo();
      foo.method(new String[]{"hello", "goodbye"}); // **array created inline**
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
13

@Hovercraft's answer shows how to create an array inline in Java.

You could further improve on that solution by using an utility method (one that makes use of Java's limited type inference) to get rid of the redundant array type annotation.

Code:

import java.util.Arrays;

// Utility class
class Array {
  public static <A> A[] of(A ... elements) {
    return elements;
  }
}

// Main class
class Main {
  public static void method(String[] s) {
    System.out.println(Arrays.toString(s));
  }

  public static void main(String[] args) {
    method(Array.of("a", "b", "c"));
  }
}
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
5

Java has varargs methods:

public void foo(String ... args){
    for(String arg : args){
        // do something
    }
}

You can call such a method with zero to n parameters, the compiler creates an array from the parameters, e.g. the method is equivalent to this Signature:

public void foo(String[] args)
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
2

No

But we have anonymous class.

foo(new Runnable(){public void run(){}});
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
jmj
  • 237,923
  • 42
  • 401
  • 438
  • You sure can create arrays inline in Java (as demonstrated by @Hovercraft's and my own answer). Regarding the anonymous class bit, how is that even relevant to the question? – missingfaktor May 22 '11 at 05:55
  • @missing what OP wants is default arg. not as arg in method call – jmj May 22 '11 at 07:44
  • 1
    @Jigar: I don't think so. See his comment under @Hovercraft's answer. He seems to have misphrased the question. I'll fix that. – missingfaktor May 22 '11 at 07:51
  • 1
    @Jigar: If the question were about default arguments, the answer would involve method overloading, and not anonymous classes. – missingfaktor May 22 '11 at 07:54
  • @missing annonymas classes are just demonstrated for F(OP)I :) – jmj May 22 '11 at 07:56