Interview Questions

Java - One or More Arguments - VarArgs

Consider a method in java, which should accept one or more arguments of same type. There are two ways to implement it. Have a look at the following code.

class Test
{
        public static void main(String[] args) throws Exception
        {
                Test test = new Test();
                test.ProcessVarArgs("str1","str2","str3");
                test.Process(new String[]{"str1","str2","str3"});
        }
       
        public void ProcessVarArgs(String st1,String...sts)
        {
                System.out.println(st1);
                for(String s:sts)
                {
                        System.out.println(s);
                }
        }
       
        public void Process(String[] sts) throws Exception
        {
                if(sts!=null && sts.length>=1)
                {
                        System.out.println(sts[0]);
                }
                else
                {
                        throw new Exception("Atleast one argument to be passes as a parameter");
                }
                for(String s:sts)
                {
                        System.out.println(s);
                }
        }
}

In the above code, both the methods perform the same functionality, but the second method by name processVarArgs is the efficient way to handle one or more arguments. The first method checks for a condition whether there is atleast one argument. This is one of the way to use varargs in java.