Java Tutorial-Java Method Parameters

Method Parameters


The data information can be passed to the functions as parameters. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separated by the commas.


Example


The following example has a method that takes an integer as parameter. When the method is called, we pass the number, which is added to the number 10 in a function.

public class MethodExample {
       static void addFunc(int a){
              System.out.println(a+10);
       }
       public static void main (String args[]){
              addFunc(3);
              addFunc(4);
              addFunc(5);
       }
}

Output

13
14
15

Return Values


The void key word, we used so far in all examples return nothing to the main function. If you want to return a value, you can use a primitive data type (such as int, char, double, etc) instead of void and the keyword return should be specified inside the method.


Example


The below method returns the value after adding with the number 10.

public class MethodwithReturnvalue {
       static int addFunc (int x){
              return 10+x;
       }
       public static void main (String args[]){
              System.out.println(addFunc(3));
              System.out.println(addFunc(4));
       }
}

 

Output

13
14

You can also pass more than one parameters to the functions.


Example – with three parameters


We pass three parameters to the function addFunc and the addition of three values are return back to the main function.

public class MethodwithReturnvalue {
       static int addFunc (int x, int y, int z){
              return x+y+z;
       }
       public static void main (String args[]){
              System.out.println(addFunc(3,4,5));
              System.out.println(addFunc(4,5,6));
       }
}

Output

12
15

You can also able to store the return value in the variable. The return value is assigned to the variable using the assignment operator.


Example – storing the return value


Here in the below example, we store the return value to the variable ‘a’.

public class MethodwithReturnvalue {
       static int addFunc (int x, int y, int z){
              return x+y+z;
       }
       public static void main (String args[]){
              int a;
              a = addFunc(3,4,5);
              System.out.println(a);
              a = addFunc(4,5,6);
              System.out.println(a);
       }
}

Output

12
15