← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 2 of 10

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

java
public class Main {
	static void greet(String name) {
		System.out.println("Hello, " + name);
	}
	public static void main(String[] args) {
		greet("Alice");
	}
}

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

java
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));
	}
}

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

java
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
	}
}

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

java
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]);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.