Lesson 15: Method Parameters, Arguments, and Pass-by-Value
Methods often need input data to perform their tasks. This data is passed via parameters and arguments.
1. Parameters vs. Arguments
- Parameters: Variables defined in the method signature (the definition) that receive the data.
- Arguments: The actual values passed to the method when it is called.
java public class Greeting { // name and hour are PARAMETERS public void greet(String name, int hour) { String timeOfDay = (hour < 12) ? "Morning" : "Evening"; System.out.println("Good " + timeOfDay + ", " + name); } }
// Calling the method Greeting g = new Greeting(); // "Sarah" and 9 are ARGUMENTS g.greet("Sarah", 9); // Output: Good Morning, Sarah
2. Java is Always Pass-by-Value
When you pass an argument to a method, Java always uses pass-by-value. This means a copy of the value is passed.
Primitives (Pass-by-Value)
If you pass a primitive type (int, double, etc.), the method receives a copy. Changes inside the method do not affect the original variable.
java public void changePrimitive(int number) { number = 99; // Changes the COPY of the variable }
int x = 10; changePrimitive(x); // x is still 10 outside the method
Objects (Pass-by-Value of the Reference)
When passing an object, Java still passes a copy of the value—but that value is the memory address (the reference) of the object.
- You can modify the object's contents: Because both the original variable and the parameter point to the same object in memory.
- You cannot change what the original variable points to: If you assign a completely new object to the parameter inside the method, the original variable outside remains unchanged.
java // Assume Person is a class with a name property public void changeObject(Person p) { p.setName("Changed Name"); // OK: Modifies the object's state
// p = new Person("New Reference"); // Fails to change the original reference
}