Parameter Passing in Java
In Java, we often pass values to methods so they can perform operations using those values. This is called parameter passing. Java supports two types of parameter passing:
- Pass-by-Value (Primitive Data Types)
- Pass-by-Reference (Objects & Arrays)
In this blog, we will cover:
- How parameters work in Java
- Passing primitive data types to methods
- Passing objects to methods
- Passing arrays to methods
- Key differences between pass-by-value and pass-by-reference
1. How Parameters Work in Java?#
In Java, all method arguments are passed by value, meaning a copy of the value is passed to the method. However, how this affects the original variable depends on whether we pass:
- Primitive data types (like
int
,double
) → Original value does not change - Objects & arrays → Original object can be modified
2. Passing Primitive Data Types (Pass-by-Value)#
When we pass a primitive data type (like int
, double
, char
) to a method, only a copy of the value is passed. Changes inside the method do not affect the original value.
Example: Passing Primitive Data Types#
Output:#
Explanation:
- Inside the method,
num
is changed, but the originalnumber
remains unchanged because only a copy was passed.
3. Passing Objects (Pass-by-Reference)#
When we pass an object to a method, a copy of the reference (memory address) is passed. This means changes made inside the method will affect the original object.
Example: Passing Objects to Methods#
Output:#
Explanation:
- The
Person
object is passed to the method, and itsname
property is changed. - Since objects are passed by reference, the original object is modified.
4. Passing Arrays to Methods#
Like objects, arrays are also passed by reference, meaning changes inside the method will affect the original array.
Example: Passing an Array to a Method#
Output:#
Explanation:
- The
modifyArray()
method changes the first element of the array. - Since arrays are passed by reference, the original array is modified.
5. Key Differences: Pass-by-Value vs Pass-by-Reference#
Feature | Primitive Data Types (int, double, char) | Objects & Arrays |
---|---|---|
Pass Type | Pass-by-Value (Copy is Passed) | Pass-by-Reference (Reference is Passed) |
Modification inside Method? | No (Original value remains same) | Yes (Original object is modified) |
Effect on Original Data | No effect | Changes are reflected |
6. Returning Values from a Method#
A method can also return modified data.
Example: Returning a Modified Value#
Output:#
Explanation:
- The method
addTen()
returns a new value, and we store it innumber
.
Conclusion#
In this blog, we learned:
- Java passes all parameters by value
- Primitive types are passed by value (original value remains unchanged)
- Objects & Arrays are passed by reference (original object is modified)
- Modifications inside methods can affect objects but not primitive types
Understanding parameter passing is important for writing efficient and bug-free Java programs.