Java Method Parameters
Single Parameter
A parameter acts like a local variable scoped to the method, automatically initialized with whatever value the caller supplies as an argument when invoking the method.
Example: Single Parameter
public class Main {
static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet("Alice");
}
}
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
Multiple parameters are separated by commas in the method signature, and the arguments you pass at the call site are matched to them strictly by position, not by name.
Example: Multiple Parameters
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(3, 5));
}
}
Login to try C/C++/Java/PHP code in the editor
Pass by Value
Because primitives are passed by value, the method works with an independent copy -- reassigning or modifying that copy inside the method has zero effect on the caller's original variable.
Example: Pass by Value
public class Main {
static void modify(int x) {
x = 100;
}
public static void main(String[] args) {
int num = 5;
modify(num);
System.out.println(num); // still 5
}
}
Login to try C/C++/Java/PHP code in the editor
Object Parameters
Object references (including arrays) are also passed by value, but that value is the reference itself -- so while you can't make the caller's variable point elsewhere, you can still mutate the object it points to, and the caller will see those changes.
Example: Object Parameters
public class Main {
static void changeFirst(int[] arr) {
arr[0] = 99; // mutates caller's array
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
changeFirst(numbers);
System.out.println(numbers[0]);
}
}
Login to try C/C++/Java/PHP code in the editor
Final Parameters
Marking a parameter final prevents the method body from reassigning it to a different value, which can catch accidental overwrites and signal to readers that the parameter's original value is meant to stay untouched throughout the method.
Example: Final Parameters
public class Main {
static void printValue(final int x) {
System.out.println(x);
// x = 10; // would not compile
}
public static void main(String[] args) {
printValue(42);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: