1

As the two functions

foo(Object... obj)
{
for(int i=0;i<obj.length;i++)
System.out.println(obj[i]);
}

and

foo(Object [] obj)
{
for(int i=0;i<obj.length;i++)
    System.out.println(obj[i]);
}

and the function call can be done

foo(obj,str,1);

foo({obj,str,1});

respectively , perform the same function and the latter existed from the very starting of java then why the Object... obj was implemented

Which one is better and why?

cornercoder
  • 276
  • 1
  • 4
  • 15

3 Answers3

5

The ... functions are a kind of syntactic sugar - they offer more convenient syntax (no braces) without alter anything else, including performance. The compiler does the same thing behind the scene, letting you use more convenient syntax.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

This won't work:

foo({obj, str, 1});

You would need to do:

foo(new Object[] {obj, str, 1});

That's awkward enough that I'm very grateful for the varargs syntax. Functionally, you are correct that they are identical.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Plus one for Syntactic Sugar... So simply it just means it's there to make your code nicer. Here is an example:

public class App {

    public static void main(String[] args) {
        Object obj = new Object();
        String str = "test";
        varArgsFoo(obj, str, 1); //Don't have to use an Array...
        varArgsFoo(new Object[]{obj, str, 1}); //But you can if it suits you.
        arrayFoo(new Object[]{obj, str, 1}); // Compiles, but you MUST pass in an Array.
        arrayFoo(obj, str, 1); // Won't compile!!! Varargs won't work if an array is expected.

    }

    /**
     * Can use simply a variable number of arguments, or an array whatever you like.
     * @param obj
     */
    static void varArgsFoo(Object... obj) {
        for (int i = 0; i < obj.length; i++) {
            System.out.println(obj[i]);
        }
    }

    /**
     * Must use an array, varargs (the ... notation) won't work.
     *
     * @param obj
     */
    static void arrayFoo(Object[] obj) {
        for (int i = 0; i < obj.length; i++) {
            System.out.println(obj[i]);
        }
    }
}
edwardsmatt
  • 2,034
  • 16
  • 18