0

I am getting an error in the below code when I change the string array argument in go method from String...y to String y[]. Can someone please explain why ?

public class scjp2 {
    public static void main(String[] args) {
        new scjp2().go( 1,"hi");
        new scjp2().go( 2,"hi", "world");
    }
    public void go( int x,String...y) {
        System.out.print(y[y.length - 1] + " ");
    }
}

Also can someone explain why do I need to have the String...y argument as the last argument in the method

example:

     public void go( int x,String...y) // correct way

     public void go( String...y,int x) // wrong way
Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
Suraj Prasad
  • 241
  • 3
  • 24
  • 2
    Because that is how it is designed. for instance: if you had (String ... y, String x), how would the compiler know which one is still part of y, which one is x ? – Stultuske Dec 16 '15 at 10:19

1 Answers1

3

You are getting an error when you change String...y to String y[] because in new scjp2().go( 2,"hi", "world"); you are not passing an array. new scjp2().go( 2,new String[]{"hi", "world"}); would work with both method signatures.

As to why a Varargs argument must be the last one - it is an optional argument, and since the mapping of passed values to method arguments in Java is done according to order, you wouldn't be able to call new scjp2().go(1); if String... y was the first argument, since 1 is not a String. On the other hand, new scjp2().go(1); works perfectly fine when the optional Varargs argument is the last argument of the method signature.

Eran
  • 387,369
  • 54
  • 702
  • 768