Java Method Parameters

Java Method Parameters and Arguments

Information can be passed to methods as a parameter. 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 separate them with a comma.


Single Parameter

The following example has a method that takes a String called fname as a parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name.

Single Parameter Example

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }

public static void main(String[] args) { myMethod("Liam"); myMethod("Jenny"); myMethod("Anja"); } }

When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments.


Multiple Parameters

You can have as many parameters as you like.

Multiple Parameters Example

public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

public static void main(String[] args) { myMethod("Liam", 5); myMethod("Jenny", 8); myMethod("Anja", 31); } }

Note: When you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.


Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method.

Return Value Example

public class Main {
  static int myMethod(int x) {
    return 5 + x;
  }

public static void main(String[] args) { System.out.println(myMethod(3)); // Outputs 8 (5 + 3) } }

This example returns the sum of a method's two parameters:

Return Sum Example

public class Main {
  static int sum(int x, int y) {
    return x + y;
  }

public static void main(String[] args) { int result = sum(5, 10); System.out.println("The sum is: " + result); // Outputs 15 } }

You can store the result in a variable (as demonstrated in the example above).