Methods can take parameters (inputs) that allow you to pass data into them. The data passed to the method is called arguments.
In Java, primitive data types (like int
, float
, char
, etc.) are passed to methods by value, meaning that a copy of the value is passed to the method. Changes made inside the method do not affect the original variable.
public class PassByValueExample {
public void modify(int a) {
a = a + 10; // This modifies the local copy of 'a', not the original
}
public static void main(String[] args) {
int num = 5;
PassByValueExample example = new PassByValueExample();
example.modify(num);
System.out.println("Original value: " + num); // Output remains 5
}
}
Original value: 5
For reference types (like arrays, objects), the reference (address) is passed to the method. This means changes to the object inside the method affect the original object.
xxxxxxxxxx
public class PassByReferenceExample {
public void modifyArray(int[] arr) {
arr[0] = 100; // Modifying the first element of the array
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
PassByReferenceExample example = new PassByReferenceExample();
example.modifyArray(numbers);
System.out.println("First element: " + numbers[0]); // Output: 100
}
}
First element: 100