๐ŸŽ“ A1Learner
๐Ÿ”

Java Method Parameters

A method parameter is a variable in a method header that receives a value from a call. The value passed at the call is the argument for that parameter.

One parameter

The greet method takes one String parameter. The call passes the text Ada as its argument.

public class Main {
  static void greet(String name) {
    System.out.println("Hello, " + name);
  }

  public static void main(String[] args) {
    greet("Ada");
  }
}

Several parameters

The describe method takes a name and an age. The call passes its two arguments in the same order.

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

  public static void main(String[] args) {
    describe("Ben", 24);
  }
}

A return value

The add method returns the sum of its parameters. Main stores that returned value and prints it.

public class Main {
  static int add(int a, int b) {
    return a + b;
  }

  public static void main(String[] args) {
    int result = add(3, 4);
    System.out.println(result);
  }
}

Example

public class Main {
  static int multiply(int a, int b) {
    return a * b;
  }

  public static void main(String[] args) {
    int product = multiply(4, 5);
    int total = product + 10;
    System.out.println(product);
    System.out.println(total);
  }
}

Key points

  • The parameter list sits in parentheses in the method header.
  • Each parameter states a type and a name.
  • Several parameters are separated by commas.
  • Arguments arrive in the same order as the parameters.
  • A method that hands a value back states that type in place of void.
  • The return statement hands a value back to the caller.

In this example, multiply takes two parameters and returns their product. The call with 4 and 5 returns 20, and main stores it in product. Main then adds 10 to that value. The printed lines show 20 and then 30.

Note

A returned value can be stored in a variable by the caller.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What does the return statement do?