1

I'm coming from a C(++) background and my main interest in Java is Android development. To me this seems like an obvious question yet I haven't found it addressed anywhere (and I did search stackoverflow and google it). What I did find was lots of comments such as:

public String foo(String key, Object[] parameters) {..}

and

public String foo(String key, Object... parameters) {..}

are equal

In fact, the java docs for "Varargs" explicitly states "The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments"

The justification most often stated, from the same source, is that varargs have "Important uses in core APIs include reflection, message formatting, and the new printf facility."

Given that Java is object oriented, includes garbage collection and supports dynamic arrays AND Java varargs are limited to a single type, whats the advantage? (In contrast to, for example, C where they implement added functionality.)

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    "Whats the advantage" over what? Over not having them, or over the array syntax? – NPE May 26 '11 at 16:14
  • See : http://stackoverflow.com/questions/4618930/what-does-mean-in-java/4618944#4618944 – jmj May 26 '11 at 16:15
  • 1
    @Vanderdeckken Well `Object... parameters` accepts whatever type you want to pass, so I do not see that is is restricted to a single type. The rules of type substitution apply here. – Edwin Dalorzo May 26 '11 at 16:18
  • 1
    In general, why use one and not the other? Specifically, why add "syntactic sugar" that not only isn't needed but actually breaks (some) preexisting code? – Vanderdeckken May 26 '11 at 16:23
  • 2
    @Vanderdeckken I am curious, how exactly varargs breaks "some" pre-existing code? – Edwin Dalorzo May 26 '11 at 16:38
  • @edalorzo It could break existing code if `foo(String,String...)` was chosen before say `foo(String,String,String)`. But it isn't, fixed arity methods are always matched first by the compiler. – biziclop May 27 '11 at 09:42

2 Answers2

8

Ease of use. Nothing more, nothing less.

printf( "...", x, y, z );

is equivalent to

printf( "...", new String[] { x, y, z } );

Except it's easier to write and to read.

biziclop
  • 48,926
  • 12
  • 77
  • 104
0

Before varargs:

log.debug( "foo is " + foo + ", bar is " + bar );

After varargs:

log.debug( "foo is %s, bar is %s", foo, bar );

Second version is much more efficient.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121