π3.6: Methods that Pass or Return Objects
Table of Contents
- Methods and Object References
- Passing Primitive Types
- Passing Objects
- Reassigning the Reference
- Summary
- AP Practice
π This page is a condensed version of CSAwesome Topic 3.6
Methods and Object References
When you pass objects to methods in Java, you are passing references to those objects, not the actual copies. This means methods can modify the objectβs state.
Passing Primitive Types
Primitive types (int
, double
, boolean
, etc.) are passed by valueβthe method gets a copy of the value, and changes do not affect the original.
Example:
public static void changeNumber(int x) {
x = 10;
}
int num = 5;
changeNumber(num);
System.out.println(num); // still 5
Passing Objects
When you pass an object, the reference is passed by value, meaning both the method parameter and the original variable point to the same object.
Example:
public static void renameDog(Dog d) {
d.setName("Max");
}
Dog myDog = new Dog("Buddy", 3);
renameDog(myDog);
System.out.println(myDog.getName()); // prints "Max"
Reassigning the Reference
If a method reassigns the parameter to a new object, the original variable is unaffected.
Example:
public static void newDog(Dog d) {
d = new Dog("Charlie", 2);
}
Dog myDog = new Dog("Buddy", 3);
newDog(myDog);
System.out.println(myDog.getName()); // still "Buddy"
Summary
- Primitives: Passed by value (copy of the data).
- Objects: Passed by value of the referenceβmethods can change the objectβs state.
- Reassigning the parameter inside the method does not change the original reference.