...

/

Method Parameters and Return Values

Method Parameters and Return Values

Learn to use parameters and return values with user-defined methods in Java.

We'll cover the following...

Method with parameters

Parameters are the input values for the method enclosed in (), provided in the method call as arguments. Multiple parameters are separated by , and each parameter must have a data type.

static void showSum(int a, int b)
{
 System.out.print(a + b);
}

The following method receives two int parameters and displays their sum:

showSum(5, 10);
Java
class Test
{
static void showSum(int a, int b)
{
System.out.print(a + b);
}
public static void main(String[] args)
{
showSum(5,10);
}
}

Array as a method parameter

An array can be received in a method as a parameter. The following program demonstrates the use of an array as a method parameter.

Java
class Test
{
static void getSum(int[] nums)
{
int c = 0;
for (int i = 0 ; i < nums.length; i++)
{
c += nums[i];
}
System.out.print(c);
}
public static void main(String[] args)
{
int nums[] = {10, 20, 30, 40};
getSum(nums);
}
}

In the program above, the method receives an array int nums[] as a parameter. We need the size to traverse through each element of the array using nums.length. We have used a for loop to calculate the sum of array elements in c and displayed it. In the main() method, we declare an array of 44 ...