Passing Objects as Arguments to Methods
In Java, when you pass an object as an argument to a method, you are actually passing a reference to the object, not the object itself. This means that the method can modify the original object's state through the reference.
In Java, when you pass a variable as an argument to a method, the mechanism used for passing depends on the type of the variable. Java uses a combination of pass-by-value and pass-by-reference mechanisms.
Pass-by-Value:
Java is primarily a pass-by-value language, which means that a copy of the value of a variable is passed to a method when you call it. Any changes made to the parameter inside the method do not affect the original variable outside the method.
Example:
public class Main {
public static void main(String[] args) {
int num = 5;
System.out.println("Before calling the method: " + num);
modifyValue(num);
System.out.println("After calling the method: " + num);
}
public static void modifyValue(int value) {
value = 10;
System.out.println("Inside the method: " + value);
}
}
Output:
Before calling the method: 5
Inside the method: 10
After calling the method: 5
In the example above, the value of num
remains unchanged after calling the modifyValue
method because it was passed by value.
Pass-by-Reference (for Objects):
In Java, when you pass an object (reference type) as an argument to a method, the reference to the object is passed by value. This means that a copy of the reference is passed, but both the original and the copy refer to the same object in memory. If you modify the object's state inside the method, the changes are visible outside the method.
Example:
public class Main {
public static void main(String[] args) {
StringBuilder name = new StringBuilder("John");
System.out.println("Before calling the method: " + name);
modifyReference(name);
System.out.println("After calling the method: " + name);
}
public static void modifyReference(StringBuilder value) {
value.append(" Doe");
System.out.println("Inside the method: " + value);
}
}
Output:
In the example above, the modifyReference
method appends " Doe" to the name
object, and this change is also visible outside the method.
It's important to note that even though the reference is passed by value, you cannot reassign the reference to a new object inside the method and have it affect the original reference outside the method. In other words, you cannot change which object the original reference points to using pass-by-reference semantics.
COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark