Java method parameters are the values that are passed to a method when it is called. These parameters are used by the method to perform some operation and return a result. In Java, there are two types of method parameters:
Primitive parameters are the basic data types in Java such as int, float, double, boolean, etc. These parameters are passed by value, which means that a copy of the value is passed to the method. Any changes made to the parameter inside the method do not affect the original value outside the method.
Reference parameters, on the other hand, are objects or arrays that are passed to the method. These parameters are passed by reference, which means that a reference to the object or array is passed to the method. Any changes made to the object or array inside the method affect the original object or array outside the method.
Here are some examples of Java method parameters:
public static void main(String[] args) {
int x = 5;
int y = 10;
int result = addNumbers(x, y);
System.out.println(result);
}
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
In this example, the addNumbers method takes two primitive parameters (int a and int b) and returns their sum. The main method calls the addNumbers method and passes two integer values (x and y) as arguments. The addNumbers method performs the addition operation and returns the result, which is then printed to the console.
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
printArray(numbers);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
In this example, the printArray method takes a reference parameter (int[] arr) which is an array of integers. The main method creates an array of integers (numbers) and passes it to the printArray method. The printArray method then loops through the array and prints each element to the console.
Java method parameters are an important concept in Java programming. Understanding how they work is essential for writing effective and efficient code.