Method Parameters
Information can be passed to methods as parameters. Parameters act as variables inside the method.
Parameters vs. Arguments
These terms are often used interchangeably, but there is a slight difference:
- Parameter: The variable defined in the method declaration
(e.g.,
String fname). - Argument: The actual value you pass when you call the
method (e.g.,
"Liam").
// 'fname' is a parameter
static void printName(String fname) {
System.out.println("Hello " + fname);
}
public static void main(String[] args) {
// "Liam" is an argument
printName("Liam");
}
Multiple Parameters
You can have as many parameters as you like, separated by commas.
static void printDetails(String name, int age) {
System.out.println(name + " is " + age + " years old.");
}
Order Matters! When you call the method, arguments must be
passed in the same order as parameters. Passing an
int where a
String is expected will cause an error.
Output
Click Run to execute your code
Values vs Variables
You can pass literal values (like 5) or variables (like
x) as arguments.
int x = 10;
myMethod(x); // Passing variable
myMethod(20); // Passing literal
Summary
- Parameters allow you to input data into methods.
- Arguments are the actual values sent to the method.
- Multiple parameters are comma-separated.
- The order and type of arguments must match the parameters.
Enjoying these tutorials?