Module 4: Methods and Code Reusability
Lesson focusMethod Parameters and Arguments: Pass-by-Value
Understand how data is passed to methods in Java, the crucial difference between passing primitive types and passing object references, and what 'pass-by-value' truly means.
Parameters vs. Arguments:
- Parameters: The variables listed in the method's definition (e.g.,
int num1, int num2). They are placeholders for the data the method expects to receive.
- Arguments: The actual values that are passed to the method when it is called (e.g.,
add(10, 20)).
Java is Strictly Pass-by-Value: This is a critical concept. It means that when you call a method, a copy of the argument's value is made and passed to the method's parameter.
Case 1: Passing Primitive Types:
- When you pass a primitive type (like
int,double,boolean), a copy of its value is passed.
- Any changes made to the parameter inside the method do not affect the original argument outside the method.
Case 2: Passing Object References:
- This is where beginners often get confused. When you pass an object (like an
Array,ArrayList, or any custom class), you are still passing a value. But the value being passed is the reference (the memory address) to the object.
- A copy of the reference is passed to the method. This means both the original reference and the parameter now point to the exact same object on the heap.
- Therefore, if you use the parameter to modify the state of the object itself (e.g., changing an element in an array), the changes will be visible outside the method because there is only one object.
- However, if you try to reassign the parameter to a new object inside the method, this will not affect the original reference outside the method. You are only changing what object the local parameter points to.
Diagram Description: A diagram showing the main method with a variable myArray pointing to an array object [1, 2] in the heap. When changeArray(myArray) is called, the changeArray method gets a new parameter arr which is a copy of the reference, also pointing to the same [1, 2] object. When the method does arr[0] = 99;, the object in the heap is modified to [99, 2], which is visible back in main.
public class PassByValueExample {
public static void main(String[] args) {
// Primitive example
int originalValue = 10;
System.out.println("Before: " + originalValue); // 10
modify(originalValue);
System.out.println("After: " + originalValue); // Still 10!
// Object reference example
int[] originalArray = {1, 2, 3};
System.out.println("Before: " + Arrays.toString(originalArray)); // [1, 2, 3]
modify(originalArray);
System.out.println("After: " + Arrays.toString(originalArray)); // [99, 2, 3]!
}
public static void modify(int number) {
number = 100; // Modifies the copy, not the original
}
public static void modify(int[] array) {
// This modifies the object that the reference points to
array[0] = 99;
}
}Lesson quiz