Results 1 to 20 of 20
Like Tree1Likes
  • 1 Post By jbarke12

Thread: Tricky code

  1. #1
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Tricky code

    Is java pass by value or pass by reference or is it both, because the examples I am referring to are confusing me? Which one of the below(Code 1 & Code 2) are pass by value and which one is pass by reference? If you say it is pass by value, please refer the codes below.

    In Code 1 the swap does not reflect in the calling method, while in Code 2 the swap is successful and values exchanged in the calling method.


    Code 1
    Java Code:
    class Test {
    	public static void swap(Person p1, Person p2) {
    		Person temp = p1;
    		p1 = p2;
    		p2 = temp;
    	}
    
    	public static void main(String args[]) {
    		Person person1 = new Person("John");
    		Person person2 = new Person("Paul");
    		System.out.println(person1.getName() + ":" + person2.getName());
    		swap(person1, person2);
    		System.out.println(person1.getName() + ":" + person2.getName());
    	}
    }
    
    class Person {
    	private String name;
    
    	Person(String newName) {
    		name = newName;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String val) {
    		name = val;
    	}
    }



    Code 2
    Java Code:
    class Test {
    	public static void resetValueOfMemberVariable(Person p1, Person p2) {
    		Person temp=new Person("Dummy");
    		temp.setName(p1.getName());
    		p1.setName(p2.getName());
    		p2.setName(temp.getName());
    		
    	}
    	public static void main(String args[]) {
    		Person person1 = new Person("John");
    		Person person2 = new Person("Paul");
    		
    		System.out.println(person1.getName()+","+person2.getName());
    		resetValueOfMemberVariable(person1, person2);
    		System.out.println(person1.getName()+","+person2.getName());
    	}
    }
    
    class Person {
    	private String name;
    
    	Person(String newName) {
    		name = newName;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String val) {
    		name = val;
    	}
    }

  2. #2
    jbarke12 is online now Member
    Join Date
    May 2013
    Location
    Charleston, South Carolina USA
    Posts
    86
    Rep Power
    0

    Default Re: Tricky code

    I know that Java is pass by value as in your code 1. So in code 1 in the swap method you could have done a print statement for p1 and p2 and they would have been switched. In code 2 the switch worked because you were using a method 'setName' to change the private value of name @ the correct address location.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Java passes by value, always; your confusion comes from the fact that for objects, their references (pointers) are passed. This may give the illusion that pass by reference is used.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: Tricky code

    your confusion comes from the fact that for objects, their references (pointers) are passed.

    Ok, Lets go with what you said. But see the quote below:

    By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter. Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program.

    Does the statement made by you not conflict with the above quote? The Code 2 swaps the values in the client program which is against the basic purpose/property of pass by value?

  5. #5
    jbarke12 is online now Member
    Join Date
    May 2013
    Location
    Charleston, South Carolina USA
    Posts
    86
    Rep Power
    0

    Default Re: Tricky code

    Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
    Last edited by jbarke12; 08-07-2014 at 02:59 PM.
    Tolls likes this.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,049
    Rep Power
    20

    Default Re: Tricky code

    As already pointed out, it's pass by value.
    You need to remember that the reference variables are pointers, so the value passed in is the pointer, not the entire contents of the object.

    If Java was pass by value then you could do:
    Java Code:
    void someMethod(MyClass myObject) {
        myObject = new MyClass();
    }
    and any code calling someMethod would find whatever variable they passed to someMethod would now be pointing at a different object on the heap.

    Also, where did you get that quote?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,657
    Rep Power
    5

    Default Re: Tricky code

    The above quote:

    "Use pass by value when when you are only "using" the parameter for some computation, not changing
    it for the client program."


    Is very misleading, if not incorrect. The programmer does not have the ability to use something which a language
    does not provide. Both C and Java pass by value, not name, because that is the way the language was designed.
    Whether you're passing pointers in C or references in Java, those values are passed by value. You have no control
    over it.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: Tricky code

    The source of the quote is:

    Function pass by value vs. pass by reference

    Also, if java is pass by value at all times then how come some times it modifies the value in the calling method whereas sometimes it doesn't?

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Quote Originally Posted by jmohandos304 View Post
    The source of the quote is:

    Function pass by value vs. pass by reference

    Also, if java is pass by value at all times then how come some times it modifies the value in the calling method whereas sometimes it doesn't?
    Reread my first reply: if you're passing a reference (i.e. a pointer to an object), your method can change the original object; for primitives you can't pass their reference.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: Tricky code

    Forget about primitives. We will come back to that later. In both Code1 and Code 2, person objects are passed as parameters. But still they have a difference that the calling method in one case has the modified value while the other case does not have the modified value. Why the difference if they are both pass by value(remember I am not talking about primitives for the time being)?

    Also is the statement below correct or not?
    Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Suppose a Person is a box; passing a Person object is passing a pointer to a box (the pointer is passed by value); Code1 tries to swap the content of (the copy of) the pointers to boxes (it fails), while Code2 swaps the content of the boxes itself (it succeeds).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: Tricky code

    So pass by value has nothing to do with whether the calling method gets the modified value or not? Are they independent?

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Quote Originally Posted by jmohandos304 View Post
    So pass by value has nothing to do with whether the calling method gets the modified value or not? Are they independent?
    Not really indeed; if the object itself is mutable, the called method can change the object (through the passed in pointer/reference). Arrays are also objects but primitives aren't, i.e. a copy of their value is passed to a method as a parameter.

    kind regarrds,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    maca is offline Member
    Join Date
    Jul 2014
    Location
    UK
    Posts
    16
    Rep Power
    0

    Default Re: Tricky code

    jmohandos304, from what I am reading from JosAH and others, the thing that is passed by value is the reference and not the actual object.

    In your case, this means that the references p1 and p2 are copied into the swap function (and not the objects to which they point), therefore the fact that you as swaping the copies around in the swap function is irrelevant to the calling code, because the original copies of the references (person1 and person2) that calling code holds remain unaffected.

    Taking a step back for further context. Consider the following code:

    Java Code:
    Person person1 = new Person("John");
    The right hand side of the equals is asking Java to create a new Person object with the argument "John"; the left hand side is asking Java to assign the address of that object to a reference called person1.

    Now consider your swap function

    Java Code:
    public static void swap(Person p1, Person p2) {
        Person temp = p1;
        p1 = p2;
        p2 = temp;
    }
    and your calling code

    Java Code:
    swap(person1, person2);
    On entrance to the swap function, Java is copying the references person1 and person2 (not the Person objects to which they point), this means that because the references person1 and person2 have been copied (i.e. passed by value) into the swap function, anything the swap code does to the references themselves (as opposed to the objects to which they point) will not be reflected in the calling code, because the swap function is acting on copies of the references (p1 and p2) and not the original references (person1 and person2).

    Therefore it is absolutely true that Java passes by value, but it just so happens that in this case (and I'm guessing any cases that are not primitives) the things being passed by value are the references, not the objects to which they point.

    I hope that helps, and if I have got anything wrong, I'm sure someone will correct me.
    Last edited by maca; 08-08-2014 at 01:53 PM. Reason: grammar

  15. #15
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,657
    Rep Power
    5

    Default Re: Tricky code

    True pass by name would work like this:

    Java Code:
    int val = 10;
    changeMe(val);
    System.out.println(val); // prints 20
    
    public void changeMe(int b) {
        b = 20;
    }
    This does not work in C or Java (even with pointers or references).
    Even if val were a reference to an object, you can't change it as above because
    you can only change what the pointer or reference refers to, not the pointer
    or reference itself.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Note that pass by name is not pass by reference; pass by name was originally a bug in Algo/60 when they tried to implement pass by reference; they did it by passing a 'thunk' which is an unnamed piece of code that was to evaluate to the actual parameter lvalue. Donald Knuth came up with an extremely filthy piece of code, named 'man or boy'. which really tortures the compiler with all the pass by name/reference/value stuff ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,657
    Rep Power
    5

    Default Re: Tricky code

    Quote Originally Posted by JosAH View Post
    Note that pass by name is not pass by reference
    I have always used the term pass by name in lieu of what other folks use to describe pass by reference.
    It may not be the same but I believe the effects are the same. The problem I find is that there is
    confusion among some about being able to pass a reference to a method vs how the compiler manifests
    access to whatever is passed. Simply stated, passing a reference is not pass by reference.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Quote Originally Posted by jim829 View Post
    I have always used the term pass by name in lieu of what other folks use to describe pass by reference.
    It may not be the same but I believe the effects are the same. The problem I find is that there is
    confusion among some about being able to pass a reference to a method vs how the compiler manifests
    access to whatever is passed. Simply stated, passing a reference is not pass by reference.
    True, and pass by name is not pass by reference; assume an array a= {1,2,3) and a variable j=1;
    Let f be a method: void f(x, y) { x++; y++; }

    If both variables are passed by reference: f(j, a[j]), then after completion of f, a == {1,3,3} and j == 2
    but for pass by name, after completion of f, a == {1,2,4} and j == 2.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,657
    Rep Power
    5

    Default Re: Tricky code

    Got it! The description of pass by name is similar to a symbolic reference in Perl. Where you would be
    passing "j" and "a[j]" to the method. "a[j]" is evaluated after "j" so the last element in "a[j]" is changed
    and not the middle, since "j" is also carried along with the "a[j]" symbolic reference (again Perl terminology).
    I hadn't considered the array example.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  20. #20
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,574
    Blog Entries
    7
    Rep Power
    21

    Default Re: Tricky code

    Quote Originally Posted by jim829 View Post
    Got it! The description of pass by name is similar to a symbolic reference in Perl. Where you would be
    passing "j" and "a[j]" to the method. "a[j]" is evaluated after "j" so the last element in "a[j]" is changed
    and not the middle, since "j" is also carried along with the "a[j]" symbolic reference (again Perl terminology).
    I hadn't considered the array example.
    Yup, that's what those 'thunks' in the pass by name mechanism do, i.e. the thunk for a[j] evaluates to, indeed a[j]; I think it's a sicko parameter passing mechanism (you can't even swap two variables with it).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Help with two tricky methods??? Please?
    By Plex66 in forum New To Java
    Replies: 1
    Last Post: 10-11-2011, 06:28 PM
  2. Need some help with tricky program
    By CGHMN in forum New To Java
    Replies: 32
    Last Post: 06-20-2011, 08:46 AM
  3. tricky initial value problem
    By Black_Eye in forum New To Java
    Replies: 4
    Last Post: 10-19-2010, 09:02 AM
  4. Tricky but very interesting problem
    By ravjot28 in forum New To Java
    Replies: 4
    Last Post: 06-26-2008, 01:43 PM
  5. tricky indexOf implementation -- Help!!
    By definewebsites in forum New To Java
    Replies: 3
    Last Post: 12-10-2007, 12:48 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •