Answer to Question #125045 in Java | JSP | JSF for Lebenis

Question #125045
What are parameters for? What is the difference between formal parameters and actual parameters? Give an example in Java code that illustrates formal parameters and actual parameters.
1
Expert's answer
2020-07-03T09:44:58-0400

Parameters are needed in order to pass values to the method. In the method, these values can be used as source data, outgoing data, and can also be changed during some operations.

Formal parameters describe the number and types of parameters that the method will take. For example, you have a function that calculates the sum of two numbers:

public static int sum(int num1, int num2)
{
    return num1+num2;
}

n this function, the formal parameters are num1 and num2, which show that the method accepts 2 parameters of type int.

When a method is called, formal parameters are replaced by actual ones.

Actual parameters are those values that are passed to the method when it is called.

For example, you call the method created above:

public static void main(String[] args) {
System.out.println( sum(10,30) );
   }

In this case, the actual parameters will be 10 and 30, which are substituted into the function instead of num1 and num2, respectively.

Substituting the actual values, we get:

public static int sum(int num1, int num2)
{
    return num1/*=10*/+num2/*=30*/;
}


And so, formal parameters are used to describe the number and types of input parameters of the method

public static int sum(int num1, int num2)


and they are also used in the method, in the code it is:

 return num1 + num2;

Actual parameters are values, which are substituted for formal parameters when calling a method.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS