Parameters
Parameters are variables that are defined in a method’s signature, allowing you to pass data into methods.
Basic Parameter Usage
Section titled “Basic Parameter Usage”public void greet(String name) { System.out.println("Hello, " + name + "!");}In this example, name is a parameter of type String.
Multiple Parameters
Section titled “Multiple Parameters”Methods can accept multiple parameters, separated by commas:
public int add(int num1, int num2) { return num1 + num2;}Parameter Types
Section titled “Parameter Types”Parameters can be of any valid Java type:
- Primitive types (int, boolean, double, etc.)
- Objects (String, ArrayList, custom classes)
- Arrays
public void processData(int id, String name, double[] values) { // Method body}Pass-by-Value
Section titled “Pass-by-Value”Java uses “pass-by-value” semantics for all parameters:
- For primitive types, a copy of the actual value is passed
- For objects, a copy of the reference is passed
public static void main(String[] args) { int x = 10; updateValue(x); System.out.println(x); // Still outputs 10
int[] arr = {1, 2, 3}; updateArray(arr); System.out.println(arr[0]); // Outputs 99}
public static void updateValue(int value) { value = 20; // Only changes the local copy}
public static void updateArray(int[] array) { array[0] = 99; // Modifies the actual array object}Variable-Length Parameters (Varargs)
Section titled “Variable-Length Parameters (Varargs)”Java supports variable-length parameter lists using ... syntax:
public int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total;}
// Can be called with any number of argumentssum(1, 2); // Returns 3sum(1, 2, 3, 4, 5); // Returns 15sum(); // Returns 0Varargs must be the last parameter in the method signature.
Final Parameters
Section titled “Final Parameters”You can declare parameters as final to prevent them from being modified within the method:
public void process(final int id) { // id = 100; // This would cause a compilation error System.out.println("Processing ID: " + id);}