Loading lessons...
Method Parameters
Method Parameters
Parameters let you pass information into a method. The method can use that data to do its work.
Parameters and arguments
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
- The method declaration lists parameters in parentheses.
- The values you pass when calling are arguments.
- Output:
Liam Refsnes,Jenny Refsnes,Anja Refsnes.
Multiple parameters
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);
}
Return values
Use return to send a value back. Replace void with the return type:
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3)); // 8
}
TL;DR
- Parameters are declared in the method signature.
- Arguments are the values passed at the call site.
returnsends a value back and defines the return type.