Tuesday, June 11, 2013

Java 1.5 Varargs

What is your impression of "..."? It's a nice little note that might come in handy. Notice how when you pass arguments from the command line ...
C:/> java MyProg a b c
You gave me 3 args!  Yay.
...
... you don't have to pass an array of stuff. The runtime automatically converts the arguments into an array of strings. You can do that now in all of your methods! For example, instead of doing this:
public class VarArgs {
  public static void main(String[] args) {
    String[] newArgs = {"a", "b", "c"};
    vaMethod(newArgs);
  }
 
  public void vaMethod(String[] args) {
    System.out.println("You gave me " + args.length + " args!  Yay.");
  }
}
You can declare it more easily, and not have to construct the array ahead of time:
public class VarArgs {
  public static void main(String[] args) {
    vaMethod("a", "b", "c");
  }
 
  public void vaMethod(String... args) {
    System.out.println("You gave me " + args.length + " args!  Yay.");
  }
}
Notice that when you use the ... syntax, it automatically treats that parameter as an array but you don't have to pass it in that way. Nifty. Let's add one of those for/in loops:
public class VarArgs {
  public static void main(String[] args) {
    vaMethod("a", "b", "c");
  }
 
  public void vaMethod(String... args) {
    for(String s : args)
      System.out.println(s);
  }

}

Read to continue :  Java 1.5 Static Import

No comments:

Post a Comment