Method Parameter Basics

When passing information from the main into a method, we have to use parameters. The parameters must be in the same order as the methods signature. The parameter list in the method signatures is the types and number of variables that the method expects to receive.

Parameters

Variables declared in a method are local to that method. In other words, they have no value oustide of the method. So, if we declare some variables in a method, and want to use their values in another method, we send them into the other method as parameters.

Say we have taken user input on the coordinates of two points in our main method as int x1, y1, x2, y2. The input assigns them a value. If we want to write a method that will find the midpoint of these two points, we need to send the values of the point in. So, in our main we see: int x1, y1, x2, y1; x1=//code for input y1=//code for input x2=//code for input y2=//code for input showMidpoint(x1, y1, x2, y2); }//end main method
In the call to showMidpoint, x1, y1, x2, and y2 are what we call the actual parameters. In other words, these are the original values that I wanted to work with.

When we declare the showMidpoint method, we need to prepare it to receive information. We do this by declaring local method variables, called formal parameters, in the parenthesis of the method signature. The signature will look like this: public static void showMidpoint(int a1, int b1, int a2, int b2) Because they are taking on copies of the values, altering the formal parameters will have no effect on the actual parameters.

So, our finished method looks like this: public static void showMidpoint(int a1, int b1, int a2, int b2) { int midX = (a1+a2)/2; int midY = (b1+b2)/2; System.out.println("The midpoint of the points is: ("+midX+", "+midY")"; }
Finally, what if we wanted to do these calculations with double values, instead of int values? We can overload the method. In other words, use the exact same signature with the exception of the type and/or number of parameters. public static void showMidpoint(double a1, double b1, double a2, double b2)
The computer will differentiate as to which version of showMidpoint to call based on the data types that are sent in.