1

I can't figure out the problem in this.

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

3 Answers3

12

A varargs argument, like String... y has to be the last variable in a method declaration. Change your declaration to:

public void go(int x, String... y) {
Keppil
  • 45,603
  • 8
  • 97
  • 119
1

There is an attempt to declare Regular parameter after the varargs parameter which is illegal.

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

Restriction of varags:

  1. varargs must be declared last

2.There must be only one varargs parameter

change your method to public void go(int x, String... y)

Community
  • 1
  • 1
Sitansu
  • 3,225
  • 8
  • 34
  • 61
1

A varargs argument must be the last variable in a method declaration

public class Trying {
    public static void main(String[] args) {
        new Trying().go(1,"hi");
        new Trying().go(2,"hi", "world");
    }
    public void go(int x,String... y) {
        for(int i=0;i<x;i++){
            System.out.println(y[i]);
        }
    }
} 

For More

Community
  • 1
  • 1
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55