In
this post we will discuss about how method calling ,value passing
happens in Java.
1.Passing
Object reference variables to a method :-
- when we pass an object to a method we are not actually passing object itself, we are passing object reference
- Reference variable holds the address location of object and a way to load into memory
- We are not passing actual reference variable,but a copy of reference variable-which holds the copy of bits present in actual value
Lets
see below code snippent
Employee
emp1=new Employee();
method1(emp1);
void
method1(Employee emp)
{
}
Here
both emp1 and emp point to same Employee Object in heap.
Example1
:-
public
class ObjectReference {
private
int
var1;
private
int
var2;
public
ObjectReference(int
x, int
y) {
var1
= x;
var2
= y;
}
public
static
void
main(String[] args) {
ObjectReference
op = new
ObjectReference(5, 10);
System.out.println("before
modify " + op.var1
+ "&&"
+ op.var2);
op.modify(op);
System.out.println("after
modify " + op.var1
+ "&&"
+ op.var2);
}
void
modify(ObjectReference pop) {
pop.var1
= pop.var1
+ 10;
pop.var2
= pop.var2
+ 10;
System.out.println("in
modify " + pop.var1
+ "&&"
+ pop.var2);
}
}
Output :-
before
modify 5&&10
in
modify 15&&20
after
modify 15&&20
Here
both op and pop reference variables are referring to same
ObjectReference
object .If one reference variable tries to change the value
autotically it gets reflected to another varaible.
In
the above example in change method we changed the value of var1 and
var2 and when we print the value in main method it got reflected.
Now
lets see what happens in case of primitive data types.
2.Passing
primitive variables to a method :-
When
we are passing primitive values to a method we are actually passing
copy of bits that represent a value.Suppose we have int a=5,when we
pass a to a method we are actually passing copy of bits of value 5.
For this we use a terminology passbyvalue rather its
passbycopyofvalue .
Example
:-
public
class
PrimitivePass {
int
a = 10;
public
static
void
main(String[] args) {
PrimitivePass
pp = new
PrimitivePass();
System.out.println("Before
change" + pp.a);
pp.change(pp.a);
System.out.println("After
change" + pp.a);
}
void
change(int
pNum) {
pNum
= pNum + 10;
System.out.println("in
change" + pNum);
}
}
output :-
Before
change10
in
change20
After
change10
From
the output we can observe that value of a is not changed ,but in
previous case we observed for object references the value has
changed.
Note
:-
- While passing an Object we actually pass copy of the object reference
- While passing a primitive type we pass the bits value stored in that variable
- In both the cases we send copy of bits,in primitives actual value is stored but in case of Object reference it stores the address of the object
Happy
Learning
Please
provide your valuable comments on this article and share it across
your network.
Contact
me @ sudheer@javarecent.com
or admin@java-recent.com
No comments:
Post a Comment