Java Pass By Value and Pass By Reference.

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.

This Core Java tutorial was added on 29/04/2008.

«

»

Comments on "Java Pass By Value and Pass By Reference." Tutorial:

  1. Abhishek Khandelwal says:

    Java is strictly ‘Pass By Value’

    • Babar says:

      NO it is both pass by value (for primitives) and pass by reference (for objects)

      • 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.

        • 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). .

        • 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).

    • 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 }

      • nikhil says:

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

      • sriram says:

        Nice explanation. Really useful

      • 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.

  2. mjt says:

    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.

  3. shiv says:

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

  4. Manoj says:

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

  5. Joe says:

    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.

    • 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.

      • 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.
        Let me know your concern:
        dewendra1@gmail.com or CTECHH-grp on FB
        We will try our best to help you 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?

  6. Vishal says:

    Hi Moderator/Owner could you please explain a bit more, the answers here sounds confusing.

    Thanks

  7. RAGASUTHA says:

    I WANTS TO KNOW THE OOPS CONCEPTS IN JAVA

  8. Priya says:

    Explanation between pass by value and java pass by reference is confusing. can you give a sample java source code?

    • 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

  9. jeRrRKKKK says:

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

  10. Anonymous says:

    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

  11. Joe says:

    @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!!

  12. ssa says:

    GOOD

  13. Mathur says:

    Good Explanation to understand the concept.

  14. gopinath says:

    CAN U ABLE TO PROVIDE ME AN EXAMPLE THAT GIVES A DIFFERENCE BETWEEN PASS BY VALUE AND PASS BY REFERNCE

  15. Arti Srivastav says:

    Do more clear bcoz it is not more clear.Difference between Pass by value and Pass by Reference.

  16. RaamNaresh Reddy says:

    Please Keep One Example Program….

    Why Java Does’nt Support pointers ????

  17. praveen says:

    thank you for your explanation

  18. Anonymous says:

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

  19. [...] 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 [...]

  20. azad says:

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

  21. 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.

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

  23. mohammad says:

    very precise, and to the point, thanks a lot

  24. parthi says:

    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.

    • Palani Arunachalam says:

      Please have a look on SCJP / OCJP book. It leads you in right way

  25. Abdelhamid says:

    Thx you a lot, it’s clear.

  26. 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?

  27. jimshad says:

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

  28. asdasd says:

    Hy Iam Hacker

  29. asdasd says:

    Hello Guyz

  30. pallav rajput says:

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

  31. venu says:

    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!

  32. Java Learner says:

    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

  33. satish kumar yadav says:

    good explanation of pass by value and pass by reference.

  34. Sadik says:

    Can U explain pass By value and pass By reference with example? I have in confusion so.

    Thanks in advance.

    • 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.

  35. Anonymous says:

    Please give easy example of pass by reference like swapping of a two number using pass by reference

  36. udhay says:

    very useful!!!

  37. Anonymous says:

    it was up to mark.
    excellent!!!!!!!

  38. MamoonRazmal says:

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

  39. ankush says:

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

  40. Azhagumuthu says:

    Yes

  41. Prabhakaran. N says:

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

  42. Anonymous says:

    your blog inter face is very nice i like it…

  43. Su says:

    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. :)

  44. Sujay Mandal says:

    Thanks , it’s very useful and nice.

  45. vinit saxena says:

    kindly give some simple examples of link list in Java

  46. 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?

  47. nanaji says:

    String s=”my name is nani”
    how can pass a string in arraylist

  48. Anonymous says:

    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.

  49. 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?

  50. 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.

  51. Rahul says:

    thanks for this explanation , but sir please explain this with the help of memory block diagram.

  52. jayapal says:

    thanks alot for this sharing of knowledge

  53. Yuvraj says:

    good for learning passing values to method

  54. navdeep says:

    its good ans. about
    what java support

  55. 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)

  56. Anonymous says:

    I DONT UNDERSTAND SO WELL!

  57. ANONYMOUS1 says:

    I DONT UNDERSTAND SO WELL!

  58. shrishti says:

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

  59. Vaibhav says:

    Good explaination

  60. 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.

  61. saravanan says:

    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

  62. Anonymous says:

    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….

  63. 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

  64. 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.

  65. Dikshita says:

    Thanks for giving good…
    Its good…

  66. 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?

  67. Aman says:

    give me answer of the following question plz.

  68. 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?????

  69. rebeen says:

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

  70. rebeen says:

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

  71. chin says:

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

  72. Anonymous says:

    please provide examples

  73. Shanker says:

    Can you elaborate the difference answer with an example.

  74. Snehal Umalkar says:

    java is pass by reference or pass by value?

  75. pratik patel says:

    please send me right answer……..

    what is the difference between pass by value and pass by reference in JAVA?????

  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. 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

  78. yogi says:

    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.

    • 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

  79. 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);
    }
    }

  80. Anonymous says:

    cgvdfg

  81. mian ehsan says:

    very important and informated site.

  82. 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=??

  83. 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]);

    }

  84. Anonymous says:

    Below is the code. Here if i am passing the object of hashmap then i am getting its updated value while in case of integer it is not like that. What is the difference between these both.
    How pass by value is working in both cases-

    public static void main(String[] args)
    {

    HashMap hm= new HashMap();
    System.out.println(hm.size()); //Print 0
    operation(hm);
    System.out.println(hm.size()); //Print 1 ; Why its updating the hashmap

    Integer c= new Integer(3);
    System.out.println(c); //Print 3
    getVal(c);
    System.out.println(c); //Print 3: Why its not updating the integer like hasmap
    }

    public static void operation(HashMap h)
    {
    h.put(“key”, “java”);

    }

    public static void getVal(Integer x)
    {
    x=x+2;
    System.out.println(x);
    }

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

↑ Go to top