Java Pass By Value and Pass By Reference

Last modified on July 8th, 2015 by Joe.

Java uses pass by value. There is no pass by reference in Java. This Java tutorial is to walk you through the difference between pass by value and pass by reference, then explore on how Java uses pass by value with examples. Most importantly we need to be clear on what we mean by using the terminology “pass by value” and “pass by reference”. Some people are saying that in Java primitives are passed by value and objects are passed by reference. It is not correct.

Pass by Value

Let us understand what is pass by value. Actual parameter expressions that are passed to a method are evaluated and a value is derived. Then this value is stored in a location and then it becomes the formal parameter to the invoked method. This mechanism is called pass by value and Java uses it.

Pass by Reference

In pass by reference, the formal parameter is just an alias to the actual parameter. It refers to the actual argument. Any changes done to the formal argument will reflect in actual argument and vice versa.

Java Language Specification Says

In Java Language Specification 8.4.1. Formal Parameters section it is stated that,

“When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.”

It is clearly evident that the actual argument expressions are evaluated and values given to the method body as formal parameters. When an object is passed as argument, that object itself is not passed as argument to the invoked method. Internally that object’s reference is passed as value and it becomes the formal parameter in the method.

Java uses JVM Stack memory to create the new objects that are formal parameters. This newly created objects scope is within the boundary of the method execution. Once the method execution is complete, this memory can be reclaimed.

Test Pass by Value vs Pass by Reference

We can run a simple swap test and check for pass by value vs pass by reference. Let us pass two arguments and swap them inside the invoked method, then check if the actual arguments are swapped. If the actual arguments are affected then the mechanism used is pass by reference otherwise it is pass by value.

public class Swap {

	public static void main(String args[]) {
		Animal a1 = new Animal("Lion");
		Animal a2 = new Animal("Crocodile");

		System.out.println("Before Swap:- a1:" + a1 + "; a2:" + a2);
		swap(a1, a2);
		System.out.println("After Swap:- a1:" + a1 + "; a2:" + a2);
	}

	public static void swap(Animal animal1, Animal animal2) {
		Animal temp = new Animal("");
		temp = animal1;
		animal1 = animal2;
		animal2 = temp;
	}

}

class Animal {
	String name;

	public Animal(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}
}

Example Output:

Before Swap:- a1:Lion; a2:Crocodile
After Swap:- a1:Lion; a2:Crocodile

Objects are not swapped because Java uses pass by value.

Swap in C++:

Same code will swap the objects in C++ since it uses pass by reference.

void swap(Type& arg1, Type& arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}

Does Java Passes the Reference?

Everything is simple and then why is this topic so hot? Now let us look at the following code where we able to change the property of a passed argument object inside a method and it gets reflected in the actual argument.

public class Swap {

	public static void main(String args[]) {
		Animal a = new Animal("Lion");

		System.out.println("Before Modify: " + a);
		modify(a);
		System.out.println("After Modify: " + a);
	}

	public static void modify(Animal animal) {
		animal.setName("Tiger");
	}

}

class Animal {
	String name;

	public Animal(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Example Output:

Before Modify: Lion
After Modify: Tiger

If the arguments are passed by value then how we are able to change an attribute of the passed argument? This is because Java passes the object reference ‘by value’. When an object is passed as argument to a method, actually the reference to that object is passed. The formal parameter is a mapping of the reference to the actual parameter.

Java Passes Reference by Value

Following figures explains method scope for variables with respect to call by value. Consider the numbers 100, 200, 600 and 700 as pointers to memory location, these are logical only and for your understanding.

call-by-value-calling-method

In figure 1, there are two objects with variable name a1, a2 which references the location 100 and 200 respectively.

call-by-value-called-method-scope

In figure 2, there are two objects named formal-arg1, formal-arg2 which references location 600 and 700 respectively. Here is the catch, contents of the location 600, 700 are again references to another location 100 and 200. So the called method has got the reference of the passed arguments. Using the reference it can manipulate only the contents of the actual argument object. But it cannot change the fact that a1 points to 100 and a2 points to 200, that’s what we are trying to do when we swap the objects.

Important point to note is that “the reference is copied as a value” to a new variable and it is given as formal parameter to the called method. It does not get a1 variable which is the actual argument in scope. This is the key difference between pass by value and pass by reference.

Comments on "Java Pass By Value and Pass By Reference"

  1. Alec says:

    Java is strictly ‘Pass By Value’. Nicely crafted tutorial.

  2. Newell says:

    For Java newbies, this explanation on java pass by reference is the best. Your example code is good to understand.

    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.

    Excellent tutorial. You should come up with Java video tutorials.

  3. shiv says:

    very good explanation on pass by value and pass by reference in java. thanks.

  4. Wallace says:

    If the callee function can change the object’s values passed, then it should be called as pass by reference right?

  5. Vishal says:

    Hi Owner this Java tutorial is excellent. You have got an excellent Java blog. What is the platform you are using?

    Thanks

  6. RAGASUTHA says:

    I want to learn OOPS via Java, can you run a tutorial series for that?

  7. Shelden says:

    Explanation for pass by value and pass by reference is cool. sample java source code helps to understand, thnks dude.

  8. Alexi says:

    java does not support pointers, thus anything is always passed by value.

  9. Nels says:

    Some sites say that, objects are are passed by reference and but the primitives are always passed by value. Now this tutorial has cleared that confusion. thanks to the author.

  10. Joe says:

    Yes Nels, everything in Java is pass by value. NOTHING is pass by reference in Java. Object references are passed by value. Since the object references are passed, it leads to the confusion.

  11. ssa says:

    GOOD

  12. Mathur says:

    Good Explanation to understand the concept.

  13. Calder says:

    You diagram is cool, looks like a drawing on green board. Good work man.

  14. Arti Srivastav says:

    It is clear for me now. Difference between Pass by value and Pass by Reference was always a confusing topic. thanks Joe

  15. RaamNaresh Reddy says:

    Example Program is simple and easy to understand.

    Why Java Does’nt Support pointers ?

  16. Bell says:

    I am a beginner migrating from C++ to Java and this really helps. I have gone through most of your Java fundamentals tutorials and they are easy to understand. thanks.

  17. Rafe says:

    Here is a 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;
    }
    }
    }

  18. […] Programming Languages’, a first class object can be stored in a data structure, passed as a parameter, can be returned from a function, can be constructed at runtime and independent of any […]

  19. azad says:

    what is the pass by reference and pass by value and pass by address

  20. Shanmukesh says:

    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.

  21. Sayf says:

    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”);
    }
    }

  22. mohammad says:

    very precise, and to the point, thanks a lot

  23. Udell says:

    i want to become a great Java developer, also want to be master in java. can you suggest some sites to learn java programs.

  24. Frey says:

    Thx you a lot, it’s clear.

  25. muthu says:

    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?

  26. jimshad says:

    **muthu
    u r ryt…and dis was d correct explanation for d new ones…

  27. Dalen says:

    Joe, this is another excellent tutorial in your Java kitty. Great going. Keep adding more.

  28. Dane says:

    Joe, is it possible for me to download all you Java tutorials in a single pdf file?

  29. pallav rajput says:

    its mean pass by reff actually using value of that reff or one copy of reff of object. m i right??

  30. Gaby says:

    This is the best article for call by value and reference. You have explained things in detail but in a simple manner. thanks.

  31. Java Learner says:

    Can you give one more example? involving Java primitive variables.

  32. satish kumar yadav says:

    good explanation of pass by value and pass by reference.

  33. Oakes says:

    excellent explanation for pass By value and pass By reference, your example is easy to understand. can you give pdf download for this article?

    Thanks in advance.

  34. Mace says:

    swap example for pass by reference is simple and easy to understand. thanks JOe.

  35. udhay says:

    very useful!!!

  36. Danny says:

    up to the mark. excellent! I am using your article in my classes to explain my students. thanks man.

  37. MamoonRazmal says:

    Thanks dude for your help in java
    But i also don’t understand the concept of”
    Stack unwinding exception”in java

  38. ankush says:

    finally in java call-by-reference is not possible is it right?

  39. Rick says:

    This is the best explanation I have found on Net. How I missed this site till now! thanks to the author.

  40. Prabhakaran. N says:

    Explanation is good.. Brief explanation about the topic from venu is also good.

  41. Quint says:

    your blog design is very nice i like it…

  42. Su says:

    Thanx to this beautiful explanation.
    @Joe: Can you please update your comment section functionality so that we can write reply to the specific comment. :)

  43. Sujay Mandal says:

    Thanks , it’s very useful and nice.

  44. vinit saxena says:

    kindly give some simple examples of link list in Java

  45. Jay says:

    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?

  46. Earl says:

    This is quality. I can see that English is not your first language, but never bother. You are doing great job.

  47. Aaron says:

    Till now I thought Java has Pass by Reference. Only primitive types (int, float etc) are passed by value. You have cleared my doubt, thanks Joe.

  48. Nitin says:

    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?

  49. Nitin says:

    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.

  50. Rahul says:

    thanks for this explanation , explanation with the help of memory block diagram is wonderful, thanks.

  51. jayapal says:

    thanks alot for this sharing of knowledge

  52. Nick says:

    Good job Joe.

  53. navdeep says:

    its good ans. about
    what java support

  54. Ved Prakash Mishra says:

    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)

  55. Jeff Dal says:

    You should collate all your Java tutorials as a Java ebook

  56. Robinson says:

    Thanks for this nice tutorial.

  57. shrishti says:

    how do you say, evn pass by reference is done, as , pass by value only ??

  58. Vaibhav says:

    Good explaination

  59. Gunasekaran says:

    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.

  60. saravanan says:

    thank you sir,i want to know about the in corba how to implement the naming service.please soon reply to mail.

  61. Nathan says:

    Reference to Java API is good and the block diagram is excellent, you got it perfect. I accidentally stumbled upon this and feeling good.thanks.

  62. Swapneel says:

    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

  63. Swapneel says:

    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.

  64. Dikshita says:

    Thanks for giving good…
    Its good…

  65. Aman says:

    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?

  66. George says:

    Joe has explained the same thing in the tutorial. You gotta read it line by line.

  67. rhea says:

    what the meaning of class, object and method?
    pls give some example class ans method and also what is used of new keyword? Can you write a tutorial for that, i have started learning Java.

  68. rebeen says:

    i want know java used for what?
    i am in the kurdistan in college technechal.

  69. rebeen says:

    please talk in arabic if you know?because i dont understand english please.

  70. chin says:

    i need to know about java static key word in broadly please can you help me.

  71. Steve says:

    Your diagram to explain call by value is too good.

  72. Shanker says:

    Can you elaborate the difference answer with an example.

  73. Snehal Umalkar says:

    java is pass by reference or pass by value?

  74. Nancy says:

    Is it “pass by value” or “call by value”?

  75. pratik patel says:

    I was asked this in the Java interview. Luckily I read it here couple of days back.

    the difference between pass by value and pass by reference cannot be explained better.

  76. Amit Dixit says:

    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.

  77. Sadasiba says:

    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

  78. Geet says:

    @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

  79. yogi says:

    hello guys,
    i hope this will help you

    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.

  80. Henry says:

    Too good

  81. Shruthi says:

    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.

  82. Babar says:

    NO it is both pass by value (for primitives) and pass by value (for objects) Joe has explained it clearly, go read it.

  83. Prasannaa says:

    Here goes the code

    import java.awt.Point;

    public class point {

    int x;
    int y;

    public static void tricky(Point arg1, Point arg2) {
    arg1.x = 100;
    arg1.y = 100;
    Point temp = arg1;
    arg1 = arg2;
    arg2 = temp;
    }

    public static void tricky1(Point arg1, Point arg2) {
    arg1.x = 100;
    arg1.y = 100;
    Point temp = new Point(arg1.x, arg1.y);
    System.out.println(“temp :: X: “+ temp.x + ” Y: ” +temp.y);
    arg1.x = arg2.x;
    arg1.y = arg2.y;
    arg2.x = temp.x;
    arg2.y = temp.y;
    }

    public static void main(String [] args) {
    Point pnt1 = new Point(0,0);
    Point pnt2 = new Point(0,0);
    System.out.println(“X: “+ pnt1.x + ” Y: ” +pnt1.y);
    System.out.println(“X: “+ pnt2.x + ” Y: ” +pnt2.y);
    System.out.println(” The users wrong way of pass by reference”);
    tricky(pnt1,pnt2);
    System.out.println(“X: “+ pnt1.x + ” Y: ” +pnt1.y);
    System.out.println(“X: “+ pnt2.x + ” Y: ” +pnt2.y);
    System.out.println(” My solution to the problem pass by reference”);
    tricky1(pnt1,pnt2);
    System.out.println(“X: “+ pnt1.x + ” Y: ” +pnt1.y);
    System.out.println(“X: “+ pnt2.x + ” Y: ” +pnt2.y);
    }
    }

  84. Fabian says:

    Best explanation with proper citation. Good work.

  85. Dewendra says:

    Hi Shruthi…
    Good Question, Have you noticed..
    After you initializing variables and printing, you are calling the static method again to make default init again which is 10,10.
    So first you are getting what you passed that is 55 but second time it’s 1010.
    Why are you thinking reference is making change to out.
    You need to understand:
    Calling a method with arguments enables you to pass some required data to the method. The question is how JVM passes these values to the method. Does it create a copy of a variable in a calling
    program and give it to the method?

  86. mian ehsan says:

    very important and informated site.

  87. Arun says:

    consider the following code in some imaginary language:

    /*main program*/
    ….
    integer i=1,j=2;
    subprog(i,j);
    print(i,j);
    ….

    subprog(integer k,integer m);
    begin
    k=k+1;
    m=m+i;
    print(i,j,k,m);
    end;

    What values would be printed in the three modes of parameter transmission? Find values below:

    IN print(i,j,k,m) in subprog()
    pass by reference – i,j,k,m=??
    pass by value i,j,k,m=??
    pass by value result i,j,k,m=??

    In print(i,j) in main program
    pass by reference – i,j=??
    pass by value i,j=??
    pass by value result i,j=??

  88. Avinash says:

    I agree with Abhishek.
    In Java be it primitive or objects, when passed in any function as argument, it is always pass by value.
    In case of objects when passed as arguments, The Object reference is copied and passed to the function.

  89. Quy says:

    Hi everyone,
    In my opinion, Java NOT strictly pass by value. It depend on different scenery.
    Thus, we have 3 option:
    + pass by primitive.
    + pass by mutable Object.
    + pass by immutable Object.
    Here an example, you can coppy and run it to show you the result.

    1 public class DemoPassByReference
    2 {
    3 public static void main(String[] args)
    4 {
    5 // Part I – primitive data types
    6 int i = 25;
    7 System.out.println(i); // print it (1)
    8 iMethod(i);
    9 System.out.println(i); // print it (3)
    10 System.out.println(“—————–“);
    11
    12 // Part II – objects and object references
    13 StringBuffer sb = new StringBuffer(“Hello, world”);
    14 System.out.println(sb); // print it (4)
    15 sbMethod(sb);
    16 System.out.println(sb); // print it (6)
    17 System.out.println(“—————–“);
    18
    19 // Part III – strings
    20 String s = “Java is fun!”;
    21 System.out.println(s); // print it (7)
    22 sMethod(s);
    23 System.out.println(s); // print it (9)
    24 }
    25
    26 public static void iMethod(int iTest)
    27 {
    28 iTest = 9; // change it
    29 System.out.println(iTest); // print it (2)
    30 }
    31
    32 public static void sbMethod(StringBuffer sbTest)
    33 {
    34 sbTest = sbTest.insert(7, “Java “); // change it
    35 System.out.println(sbTest); // print it (5)
    36 }
    37
    38 public static void sMethod(String sTest)
    39 {
    40 sTest = sTest.substring(8, 11); // change it
    41 System.out.println(sTest); // print it (8)
    42 }
    43 }

  90. satyajit kumar sethy says:

    Pass by value : will change/reflect locally, within method execution original value of variable will be remains same.

    Pass by references: when will be passed to a method the value of address/references will be passed, so if changes will made then the value on that location will be changed.
    Conclusion : In java always pass by value.

  91. Joe says:

    Thanks guys for all your nice words.

  92. Farrs says:

    I am preparing for OCJP, can you tutor me over skype?

  93. chandu says:

    hi one more example to prove that java is pass by Reference and pass by value.
    o/p
    before passByReference1
    After passByReference22
    before passByValue2
    After passByValue2

    public class ArrayAsPassByValue {

    public static void passByReference(int arr[])
    {
    arr[0] = 22;
    }
    public static void passByValue(int arr)
    {
    arr = 22;
    }
    public static void main(String[] args) {

    int [] arr = {1,2,3,4};

    System.out.println(“before passByReference”+arr[0]);
    passByReference(arr);
    System.out.println(“After passByReference”+arr[0]);

    System.out.println(“before passByValue”+arr[1]);
    passByValue(arr[1]);
    System.out.println(“After passByValue”+arr[1]);

    }

  94. chandu says:

    hi.here your doing shallow copy not deep copy of Object means your changing reference of object.
    .

    1 arg1.x = 100;
    2 arg1.y = 100;
    3 Point temp = arg1;
    4 arg1 = arg2;
    5 arg2 = temp;

    in line number 3 your temp reference variable refers arg1 object. so it’s not creates new object instance. in line 4 arg1 refers arg2 object. and in line number 5 arg2 reference variable refers to (old arg1 object it’s still exist because temp reference variable refers it).
    so java is also call by reference

  95. Eldred says:

    thanq..this is a very useful example..:) i clearly understood the concept..

  96. govind says:

    yes i am also agree with Abhishek. call by value means copy the value whatever that variable contains and call by ref means passing the address of that variable in C/C++ language call by ref achieved by ‘&’ operator e.g call(&a). .

  97. Stan says:

    Nice explanation. Really useful

  98. Rashid Khan says:

    The value for an object refers to the object reference, not its state. So, you can change the internal state of the passed mutable object, but you cannot change the reference itself. So Java is ALWAYS PASS BY VALUE.

  99. Jake says:

    The best article on pass by value and reference for Java

Comments are closed for "Java Pass By Value and Pass By Reference".