Java Method Parameters

Method Parameters:

They define what type of data the method expects to receive as input. Parameters allow methods to be more flexible and reusable, as different values can be passed to the method each time it is invoked.

The syntax for method parameters:

// method with parameters

accessModifier returnType methodName(parameterType1 parameterName1, parameterType2 parameterName2, …) {

// method body

}

Method Arguments:

The syntax for method arguments:

methodName(argumentValue1, argumentValue2, …);
Parameter and Argument:
  1. Parameter: In the method signature public static int square(int number), the parameter is defined as int number. It specifies that the method square expects an input value of type int, which will be referred to as number inside the method body.
  2. Argument: In the main method, when we call the square method using square(num), we pass the value of the variable num (which is 5) as an argument to the square method. This value is used as the number parameter in the square method for calculating the square.

Multiple Parameters:

Let’s build a Java program that uses a method with multiple parameters We will define a method called calculateSum that takes two integers as parameters, and we will use specific arguments to calculate the sum of two numbers using this method:

Multiple Parameters and Arguments:

In the calculateSum method, we defined two parameters num1 and num2. When calling the calculateSum method in the main method, we passed two arguments a and b as inputs. These arguments match the order and type of the parameters in the method’s signature. The method then uses these arguments to perform the addition and return the sum, which is then printed to the console.

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close