Results 1 to 2 of 2
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Question on Passing by Reference..

    Java Code:
    public class PrintingContainers {
    	
    	static Collection fill(Collection<String> collection,String a,String b) {
    		collection.add(a);
    		collection.add(b);
    		return collection;
    	}
    	
    	public static void main(String[] args)
    	{
    		ArrayList<String> myArrayList = new ArrayList<String>();
    		System.out.println(PrintingContainers.fill(myArrayList,"Tolls","Fuburable"));
    		System.out.println(myArrayList);
    	}
    }
    My question is,

    When I call the fill method I pass an argument: myArrayList.

    When the fill method is called, does it mean that

    collection and myArrayList reffers to the same object?
    And collection changes some values in the object that myArrayList is refering to as well?

    Is this what is meant by pass by reference ?

    So during the method call, there are two references pointing to the same object ?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Question on Passing by Reference..

    Java has only pass-by-value. There's no pass-by-reference in Java.

    -- primitives are passed by value
    -- references are passed by value
    -- objects aren't passed at all

    In your example, the value of the reference is copied to the parameter. Yes, there are now two equal references, and references are only equal if they refer to the same object. That's not pass-by-reference at all.

    For an easy-to-understand version, go through this page on another forum, and the next lesson linked from the bottom of that page: JavaRanch Campfire - Cup Size: a Story About Variables

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 1
    Last Post: 10-27-2011, 07:21 AM
  2. Replies: 14
    Last Post: 07-21-2011, 08:56 PM
  3. Don't pass by reference
    By Lyven in forum Advanced Java
    Replies: 6
    Last Post: 11-16-2009, 06:06 PM
  4. Object and reference
    By katie in forum New To Java
    Replies: 2
    Last Post: 10-19-2009, 03:45 PM
  5. Passing Class Reference to method
    By nekt in forum Advanced Java
    Replies: 5
    Last Post: 03-26-2009, 05:08 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
  •