0

Why method varargs must be in separate from main method body? Below code is correct, but why can't I put varargs method declaration in the main method body?

public class TryVariableArgumentList {

    public static void main(String[] args) {
        x("first","second");

        public static void x(String... list) {
            for (String y : list)
                System.out.println(y);
        }
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
  • 1
    possible duplicate of [Why doesn't Java's main use a variable length argument list?](http://stackoverflow.com/questions/2201696/why-doesnt-javas-main-use-a-variable-length-argument-list) – Thomas Jungblut Jan 11 '15 at 12:41

2 Answers2

4

the method

public static void main(String... args) {
    //code
}

is also perfectly legal

The problem with the code is Method declaration inside a method itself is not allowed in Java

Compilable code has to be like this

class TryVariableArgumentList {
    public static void main(String[] args) {
        x("first","second");
    }

    public static void x(String... list) {
        for(String y : list)
            System.out.println(y);
    }
}

I think you need to post what you read,because maybe you have interpreted something incorrectly

Hope this helps!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vihar
  • 3,626
  • 2
  • 24
  • 47
0

Your method x is declared in method main. This is not legal. Declare x outside of main.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319