29/04/2008
Pass by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments are always passed by value. Java only supports pass by value.
With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.
Ads by Google











Java is strictly ‘Pass By Value’
For Java newbies, this explanation on java pass by reference can be confusing. It would be
better to explain by example. The reason is because with Java
primitives, the results are different than with objects.
The problem comes in because, for primitives, the value of the
argument can be altered (in the method), but it doesn’t affect the
source variable. With an object reference being passed, that
object can be operated on (in the method) and its values changed.
Big difference.
very good explanation on pass by value and pass by reference in java. thanks.
not bad
If the callee function can change the object’s values passed, then it should be called as pass by reference right?
Yes Manoj. You are exactly right. If the passed object’s state can be changed so that it gets reflected in the caller method then it is called pass by reference. Java doesn’t has pass by reference. It is strictly pass by value.
public class StrBClass
{
int a,b;
public static void abc(StrBClass s)
{
s.a = 10;
s.b = 10;
}
public static void main(String[] args)
{
StrBClass st = new StrBClass();
st.a = 5;
st.b = 5;
System.out.println(st.a+” “+st.b);
abc(st);
System.out.println(st.a+” “+st.b);
}
}
Hi Joe,
I`m new to this site. I think java has both pass By Value and pass By reference.
It passes primitive type in pass By value way and objects in pass by reference way. Above pgm illustrates the same. Please provide your comments. Thanks.
Hi Moderator/Owner could you please explain a bit more, the answers here sounds confusing.
Thanks
Got the answer here..
CHeck this out.
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
I WANTS TO KNOW THE OOPS CONCEPTS IN JAVA
Explanation between pass by value and java pass by reference is confusing. can you give a sample java source code?
When we pass one object as the parameter of a method then it passes the object as value not as reference, it passes the object as copy so any changes of data in the copy of the object changes the data in the original object, but change in copy of the object does not changes the object.
Example
public class CallByRefTest{
public static void main(String args[]){
A a1 = new A();
method(a1);
System.out.print(a1.i);//here o/p is 7 bcos we can change the field of object
method1(a1);
System.out.print(a1.i);//here o/p is
}
public static void method(A a2){
System.out.print(a2.i);
a2.i = 7;
}
public static void method1(A a3){
System.out.print(a3.i);
a3 = new A();
a3.i = 9;
}
}//o/p 57 we can change the data of object by reference
//o/p 77 we can not change value of object
java does not support pointers, thus anything is always passed by value.
Yes There is pass by reference in java..
Reference are passed by value to the function is nothing but pass by reference…. but the primitives are always passed by value
@Anonymous – everything in java is pass by value. NOTHING is pass by reference in java. Even the references are passed by value only.
Kindly read the whole article. Its simple and small!!
GOOD
Good Explanation to understand the concept.
CAN U ABLE TO PROVIDE ME AN EXAMPLE THAT GIVES A DIFFERENCE BETWEEN PASS BY VALUE AND PASS BY REFERNCE
Do more clear bcoz it is not more clear.Difference between Pass by value and Pass by Reference.
Please Keep One Example Program….
Why Java Does’nt Support pointers ????
thank you for your explanation
Here is the sample program
public class TestPassByReference {
/**
* @param args
*/
public static void main(String[] args) {
Reference ref = new Reference();
System.out.println(“The reference of ref=” + ref);
System.out.println(“The reference of ref=” + ref.name);
getValue(ref);
System.out.println(“The reference of ref=” + ref.name);
System.out.println(“The reference of ref=” + ref.getName());
}
public static void getValue(Reference r) {
r.setName(“Prashant”);
}
public static class Reference {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void Reference(String name) {
this.name = name;
}
}
}
Pingback: Java Closures
what is the pass by reference and pass by value and pass by address
Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
An arraylist and other types of collections do not neccesarly contain objects but it contains refrences to Objects, so you can use an ArrayList to pass refrences in Java, example:
public class Book {
String title;
public Book(String title){
this.title = title;
}
public void setTitle(String newTitle) {
this.title = newTitle;
}
public String getTitle() {
return this.title;
}
}
public class Example {
public static void main(String[] args){
Example example = new Example();
ArrayList bookList = new ArrayList();
bookList.add(0, new Book(“First book”));
bookList.add(1, new Book(“Second book”));
bookList.add(2, new Book(“Third book”));
//we pass an object containing refrences :)
example.demonstrate(bookList);
//proof that its not only pass by value
System.out.println(bookList.get(0).getTitle());
}
public void demonstrate(ArrayList aBookList){
aBookList.get(0).setTitle(“Changed the First title by refrence”);
}
}
ljknjn
very precise, and to the point, thanks a lot
i want to become a great java developer,also want to be master in java program.can u suggest some sites to learn java code properly.
Thx you a lot, it’s clear.
As I understand, Java is strictly supports pass by value .
If variable is passed as argument inside a method, copy of the value is passed. So, it will not affect the original value of variable (for primitive types).
But, if object reference is passed, copy of the value of memory address is passed. So, we able to change the value of an object.
Joe, Is my understanding right?
@Muthu : very gud expn..
**muthu
u r ryt…and dis was d correct explanation for d new ones…
Hy Iam Hacker
Hello Guyz
its mean pass by reff actually using value of that reff or one copy of reff of object. m i right??
I found this over the net. Quite a nice explanation.
This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you’ll just smile :-)
Step one please erase from your mind that word that starts with ‘p’ “_ _ _ _ _ _ _”, especially if you come from other programming languages. Java and ‘p’ cannot be written in the same book, forum, or even txt.
Step two remember that when you pass an Object into a method you’re passing the Object reference and not the Object itself.
Student: Master, does this mean that Java is pass-by-reference?
Master: Grasshopper, No.
Now think of what an Object’s reference/variable does/is:
A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.
So you’re just passing 3bad086a that it’s the value of the reference.
You’re passing the value of the reference and not the reference itself (and not the object).
This value is actually COPIED and given to the method.
In the following (please don’t try to compile/execute this…):
1. Person person;
2. person = new Person(“Tom”);
3. changeName(person);
4.
5. //I didn’t use Person person below as an argument to be nice
6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
7. anotherReferenceToTheSamePersonObject.setName(“Jerry”);
8. }
What happens?
The variable person is created in line #1 and it’s null at the beginning.
A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let’s say 3bad086a.
The variable person holding the address of the Object is passed to the function in line #3.
In line #4 you can listen to the sound of silence
Check the comment on line #5
A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:
The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.
No new instances of Person are created.
Both “person” and “anotherReferenceToTheSamePersonObject” hold the same value of 3bad086a.
Don’t try this but person==anotherReferenceToTheSamePersonObject would be true.
Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.
A picture is worth a thousand words:
Pass by Value
Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!
If you didn’t get it then just trust me and remember that it’s better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)
Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.
You always pass a copy of the bits of the value of the reference!
If it’s a primitive data type these bits will contain the value of the primitive data type itself.
If it’s an Object the bits will contain the value of the address that tells the JVM how to get to the Object.
Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you’ll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!
The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.
Of course you can cut it short and just say that Java is pass-by-value!
Not at all good explanation. I had to search on other sites / forum to get more detailed understanding.
Please elaborate with examples, like you do in other posts
good explanation of pass by value and pass by reference.
Can U explain pass By value and pass By reference with example? I have in confusion so.
Thanks in advance.
Please give easy example of pass by reference like swapping of a two number using pass by reference
very useful!!!
it was up to mark.
excellent!!!!!!!
Thanks dude for your help in java
But i also don’t understand the concept of”
Stack unwinding exception”in java
finally in java call-by-reference is not possible is it right?
Yes
Explanation is good.. Brief explanation about the topic from venu is also good.
your blog inter face is very nice i like it…
Thanx to Venu for this beautifull explanation.
@Joe: Can you please update your comment section functionality so that we can write reply to the specific comment. :)
Thanks , it’s very useful and nice.
kindly give some simple examples of link list in Java
Explain the statement ‘java is strictly pass by value’ consider the below piece of code:
import java.util.*;
public class A{
public static void main(String args[]){
ArrayList a=new ArrayList();
a.add(“1″);
System.out.println(a);
somemethod(a);
System.out.println(a);
}//main
public static void somemethod(ArrayList a){
a.add(“2″);
}
}//class
The output of this code will be:
[1]
[1, 2]
Since a reference to the arraylist was passed into the method….no?
String s=”my name is nani”
how can pass a string in arraylist
Please don’t pass false information.
Java has Pass by Reference. Only primitive types (int, float etc) are passed by value. All the other objects in JAVA are passed by REFERENCE only.
I am posting same issue
Explain the statement ‘java is strictly pass by value’ consider the below piece of code:
import java.util.*;
public class A{
public static void main(String args[]){
ArrayList a=new ArrayList();
a.add(“1″);
System.out.println(a);
somemethod(a);
System.out.println(a);
}//main
public static void somemethod(ArrayList a){
a.add(“2″);
}
}//class
The output of this code will be:
[1]
[1, 2]
Since a reference to the arraylist was passed into the method….no?
Ok I explain myself here…>>>
import java.util.*;
public class A{
public static void main(String args[]){
line1: ArrayList a=new ArrayList();
line2: a.add(“1″);
line3: System.out.println(a);
line4: somemethod(a);
line5: System.out.println(a);
}//main
line6: public static void somemethod(ArrayList a1){
line7: a1.add(“2″);
}
}//class
Explaination:-
line1:- an arrayList variable ‘a’ created and assigned to ArrayList Object.
line2:- a has got its first element, “1″
line3:- It prints [1]
line4:- Here is the magic. It seems that whole ‘a’ is being passed in the method ‘somemethod’, but its not true.
Here actually memory address lets say 3bad086a is being passed.
line6:- I explain line6 before line5 because it goes to here first.
Following is the fact about line6:-
(1) a1 is the local variable/reference.
(2) The variable/reference ‘a’ is copied bit-by-bit and passed to a1.
(3) No new object of ArrayList is created.
(4) Both ‘a’ and ‘a1′ hold the same memory address 3bad086a. If you try a==a1, it will return true.
(5) So both ‘a’ and ‘a1′ refer to the same object.
line7:- Since a and a1 both represent same object a1.add(“2″) is same as a.add(“2″).
line5:- method ‘somemethod’ returns and now 2 elements will be shown
Conclusion:- Java always has pass by VALUE not reference.Because its VALUE that is being in method NOT object.
thanks for this explanation , but sir please explain this with the help of memory block diagram.
thanks alot for this sharing of knowledge
good for learning passing values to method
its good ans. about
what java support
Clearly explained in below link for both newbies and experienced
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Thanks a lot joe…your every paper in Java is Tramendous, i used to read this coz it’s very simple and easy to understand the basics of any topic in core java.
Thanks again..
From VED Prakash Mishra(ICS,B’lore)
I DONT UNDERSTAND SO WELL!
I DONT UNDERSTAND SO WELL!
how do you say, evn pass by reference is done, as , pass by value only ??
Good explaination
I think instead creeping around if Java supports pass by reference or values, one should be clear about the way of using the instances of the classes in Java in his implementation. It all happens to be the type of instances – mutable/immutable which is gonna decide the way we pass things to the functions! That’s up to you to explore this difference!
Let me clarify my argument of why there is no need of chasing back at passing what?! Consider this…
/*First Code*/
void foobar(int *a){
printf(“%d”, *a);
}
int main(){
int a = 5;
foobar(&a);
return 0;
}
Here in this C code, what are you passing… the address of the variable ‘a’. This happens to be the pass by reference! :)
Let us consider another one…
/*Second Code*/
void foobar(int* a){
printf(“%d”, *a);
}
int main(){
int a = 5;
int *p = &a;
foobar(p);
return 0;
}
Here in this C code, what am I passing….? The value of the variable ‘p’, doesn’t matter whether it is pointer or something :P
So what do you call this as pass by value/pass by reference? I leave this to you! But all we need to look at is how we gonna implement… :)
So in Java… with what we pass we can say – It supports “Pass by value” or “Pass by reference of some instance” and not “Pass by reference”
***Only thing which I can clearly conclude is with the primitive data types in Java. Since there is no pointers with which one can edit the content of a byte without the actual variable, we can’t have pass by reference for them(I mean the primitive data types) in Java.
thank you sir,i want to know about the in corba how to implement the naming service.please soon reply to mail.is very urgent sir
please give the simple example of pass by value and pass by reference.and plz also explain the theoretical difference between them……….may be possible…….replay should be fast….
pass by value eg:
int x=10;
int y=x;
the above code is pass by value where the value contained in x is copied in y.
It means y has its own copy and does not point to the location where x points.Do if you change x it will not affect y and vice-versa
Java is always Pass by Value.
The above was for primitives but incase of objects also java performs pass by value.
String s1=new String(“JAVA”);
String s2=s1;
In the above case both s1 and s2 are pointing to the same Object on heap.
Here the object is not copied but the reference to object is copied annd stored in s2.
SO incase of Objects the reference are copied and not the actual object.
Thanks for giving good…
Its good…
package com.app.concept;
public class CallByRef {
static int a, b;
public CallByRef() {
a = 10;
b = 20;
}
static void swap(CallByRef obj) {
int temp;
temp = CallByRef.a;
CallByRef.a = CallByRef.b;
CallByRef.b = temp;
System.out
.println(“In the swap() method obj has the value of and b are:”);
System.out.println(“a=” + CallByRef.a + “\t” + “b=” + CallByRef.b);
}
public static void main(String[] args) {
CallByRef obj1 = new CallByRef();
System.out.println(“Before swapping value of a and b in obj1″);
System.out.println(“a=” + CallByRef.a + “,” + “b=” + CallByRef.b);
swap(obj1);
System.out.println(“After swapping value of a and b in obj1″);
System.out.println(“a=” + CallByRef.a + “,” + “b=” + CallByRef.b);
}
}
/*
Before swapping value of a and b in obj1
a=10,b=20
In the swap() method obj has the value of and b are:
a=20 b=10
After swapping value of a and b in obj1
a=20,b=10
*/
My question is in both object has change te value whereas i change the value in obj.
Here change the value of obj but obj1 also change the original value.
Can i say this is call by reference (or not)and why?
give me answer of the following question plz.
what the meaning of class, object and method??????????
pls give some example class ans method and also what is used of new keyword?????
i want know java used for what?
i am in the kurdistan in college technechal.
please talk in arabic if you know?because i dont understand english please.
i need to know about java static key word in broadly please can you help me.
please provide examples
Can you elaborate the difference answer with an example.
java is pass by reference or pass by value?
please send me right answer……..
what is the difference between pass by value and pass by reference in JAVA?????
Java is pass by value
Lets validate the above line by an example:
int a = 10 ;
System.out.println(“value of a before assignment” + a); // it will print 10
int b = a ;
b = 30;
System.out.println(“value of a after assignment” + a); // it will also print 10
So conclusion is this that when you assign value of one primitive to an another primitive variable then you are passing a copy.
Now lets play similarly with references of an object
Dimension a = new Dimension(10,20);
System.out.println(a.height + “” + a.width); // it will print 10 20
Dimension b = a
b.height = 5 ;
System.out.println(b.height + “” + b.width); // it will print 5 20
System.out.println(a.height + “” + a.width); // it will print 5 20
So conclusion is that when we assign one reference to another object reference then any of the refernces can change the state of an object.
@Joe
ArrayList a = new ArrayList();
a.add(“xyz”);
ArrayList b = a;
b.clear();
System.out.println(b.toString());
System.out.println(a.toString());
RESULT:
[]
[]
Above example make sense for me.
Now, take a look, I am confuse in below example, this is an insert method for singly linked list.
Link first=null
public void insert(String s1, Strings2,double d3){
Link link=new Link(s1,s2,d1);
link.next=first;
first=link;
}
Here I am assigning first in link.next(link.next=first;) and in next line I assign link to first(first=link). So I think link.next will point to link it self, which is not.
Can you please explain me this issue?
Thanks
hello guys, i am above Anonymous
i hope this will help more for your confusion.
just a simple example
public class point
{
int x,y;
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
line 1:System.out.println(“X: ” + pnt1.x + ” Y: ” +pnt1.y);
line 2:System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky(pnt1,pnt2);
line 3:System.out.println(“X: ” + pnt1.x + ” Y:” + pnt1.y);
line 4:System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
}
}
just think there is a pass by reference in java. the output at line 4 will be 100 and 100 but it gives 0 and 0. so there is no pass by reference in java.