• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

var-args (...)

 
Angel Fontanet
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I want to know How this var-args (...) works?

Thanks a lot
 
ashni Prakash
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi angel,

Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

To pass an arbitrary number of values to a method you use parameters called varargs. You use varargs when you don't know how many of a particular type of argument will be passed to the method.

To declare varargs use type followed by an ellipsis(threedots...)give some space and then name of parameter.


The code below explain varargs:
-----------------------------------------------------------------
public Polygon polygonFrom(Point... corners) {
int numberOfSides = corners.length;
double squareOfSide1, lengthOfSide1;
squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x)
+ (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
lengthOfSide1 = Math.sqrt(squareOfSide1);
// more method body code follows that creates
// and returns a polygon connecting the Points
}

--------------------------------------------------------------------------
code

In above example (Point... corners)is a varargs parameter passed to a method polygonForm.
 
ashni Prakash
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
varargs is just like creating an array manually.The code given by me above is equivalent to the one below:

public Polygon polygonFrom(Point[] corners) {
// method body goes here
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, not just like creating it manually. For one thing, using your first example, you can all the method like this:

Here a Point[] array is created for you, without you needing to write the code for it. But with your second example (non-varargs), you need to create the array yourself:

There are a few other differences as well.

Angel, other good places to learn about varargs include the JDK 5 release notes and the Java tutorial.
 
Angel Fontanet
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Jim and Praks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic