Skip to content

Parameters

This content is for Java. Switch to the latest version for up-to-date documentation.

Parameters are variables that are defined in a method’s signature, allowing you to pass data into methods.

public void greet(String name) {
System.out.println("Hello, " + name + "!");
}

In this example, name is a parameter of type String.

Methods can accept multiple parameters, separated by commas:

public int add(int num1, int num2) {
return num1 + num2;
}

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
}

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
}

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 arguments
sum(1, 2); // Returns 3
sum(1, 2, 3, 4, 5); // Returns 15
sum(); // Returns 0

Varargs must be the last parameter in the method signature.

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);
}
Built with passion by Ngineer Lab