So I just learned about varargs on the Java Oracle tutorial, and I am having trouble reading this code. For example, what is "(Point... corners)" I know it is a shorten version of (Point[] corners) but what is "Point"? Is it an array that tells us about some (x,y) coordinate(s) that we define? Also, I do not understand what"(corners[1].x)" means. What is that dot notation ".x and .y", and what is exactly happening with the other "corners"? Sorry for all the questions, I know they may seem like a stupid questions, but I, nevertheless, thank you for your time.

``public Polygon polygonFrom(Point... corners) {int numberOfSides = corners.length;double squareOfSide1, lengthOfSide1;// The "corners" array dot notations below are what confuse me the most.// There are values stored in each index correct?//So "corner[1].x could contain element 6 right?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``

}

From the tutorial:

assume that Point is a class that represents an x, y coordinate

So, `Point` is a hypothetical class that looks like this:

``````class Point {
int x;
int y;
}
``````

The `Polygon` class is constructed from an arbitrary array of points. The syntax `corners[1].x` returns the value of the `x` field on the second `Point` object in the `corners` array.

note that `Point... points` is not exactly a shorten for `Point[] points` in fact the first can only be the last argument of a function, the second, instead, can be in any position. For example is legal to write a function like the following

``````public void foo(Point[] points, int arg2){}
``````

but is not legal to write

``````public void foo(Point... points, int arg2){}
``````

Back to your problem, consider the following Point class (as pointed out in the tutorial):

``````public class Point
{
public int x;
public int y;
}
``````

then be `Point... corners` an array of points then with the syntax `corners[i]` (with i >= 0 and i < corners.length) you access the i-th element of the array (remember that array indices starts from 0 and not from 1). So if you scompose the command `corners[i].x` you get

``````Point p = corners[i];
int xcord = p.x
``````

and i think this is much clearer for you, in fact the command first take the i-th element of the array and than the x coordinate of that element.

Hope it's all clear. I suggest to start from the ground of java if you never programmed before. This is a nice place where to start --> http://www.tutorialspoint.com/java/

Top