aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes var-args (...) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "var-args (...)" Watch "var-args (...)" New topic
Author

var-args (...)

Angel Fontanet
Greenhorn

Joined: Dec 06, 2006
Posts: 10
Hi

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

Thanks a lot
ashni Prakash
Ranch Hand

Joined: Dec 05, 2006
Posts: 50
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

Joined: Dec 05, 2006
Posts: 50
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
Angel Fontanet
Greenhorn

Joined: Dec 06, 2006
Posts: 10
Thanks a lot Jim and Praks
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: var-args (...)