What are parameters in Java?

A parameter is a variable that is used to define a particular value in the method declaration. The parameters act as variables inside the method.

Parameters are specified in the method name inside the parentheses. There can be one or more parameters separated with a comma.

Each parameter has two parts - data type and the variable name. The data type followed by the variable name defines the type of value that can be passed to the method when it is called. It is also called as a formal parameter.

Parameters declared in the method are always local variables that receive values when the method is called from another method.

For example

int sum(int x, int y)
{
return(x + y);
}

In the method sum, x and y are the two parameters of int data type. The method adds the values passed in the parameters and returns the result to the caller method.

While passing the argument values to the parameters, the order of parameters and the number of parameters is very important. The order must be the same as the parameters declared in the method declaration.

public class Example {
  public static void main(String[] args) {
    Example obj = new Example();
    int x = obj.sum(50, 80);
    System.out.println("Result: " + x);
  }
  int sum(int a, int b) {
    return a + b;
  }
}

The output is

Result: 130

Varargs

Varargs is the abbreviation of variable arguments. An argument of a method can accept an arbitrary number of values. This argument which can accept n number of values is called varargs.

To define a varargs, three dots(...) are used in the formal parameter of the method.

The syntax is

access_modifier return_type method_name(data_type...var_name){
}

A method that takes a variable number of arguments is called varargs method. If the user does not know how many arguments have to be passed in the method, varargs is the best approach.

public class Demo {
  public int sum(int...num) {
    int sum = 0;
    for (int x: num) {
      sum += x;
    }
    return sum;
  }
  public static void main(String[] args) {
    Demo d = new Demo();
    int result1 = d.sum(6, 7, 8);
    System.out.println("Result1 = " + result1);
    int result2 = d.sum(13, 15, 17, 19);
    System.out.println("Result2 = " + result2);
    int result3 = d.sum(120, 140, 160, 180, 200);
    System.out.println("Result3 = " + result3);
  }
}

The output is

Result1 = 21
Result2 = 64
Result3 = 800
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions