Can you pass by reference in Java?

Posted by dbones on Stack Overflow See other posts from Stack Overflow or by dbones
Published on 2009-11-17T12:19:25Z Indexed on 2010/04/28 21:17 UTC
Read the original article Hit count: 330

Filed under:
|
|
|

Hi.

Sorry if this sounds like a newbie question, but the other day a Java developer mentioned about passing a paramter by reference (by which it was ment just pass a Reference object)

From a C# perspective I can pass a reference type by value or by reference, this is also true to value types

I have written a noddie console application to show what i mean.. can i do this in Java?

namespace ByRefByVal
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating of the object
            Person p1 = new Person();
            p1.Name = "Dave";
            PrintIfObjectIsNull(p1); //should not be null

            //A copy of the Reference is made and sent to the method
            PrintUserNameByValue(p1);
            PrintIfObjectIsNull(p1);

            //the actual reference is passed to the method
            PrintUserNameByRef(ref p1);    //<-- I know im passing the Reference
            PrintIfObjectIsNull(p1);

            Console.ReadLine();
        }

        private static void PrintIfObjectIsNull(Object o)
        {
            if (o == null)
            {
                Console.WriteLine("object is null");
            }
            else
            {
                Console.WriteLine("object still references something");
            }
        }

        /// <summary>
        /// this takes in a Reference type of Person, by value
        /// </summary>
        /// <param name="person"></param>
        private static void PrintUserNameByValue(Person person)
        {
            Console.WriteLine(person.Name);
            person = null; //<- this cannot affect the orginal reference, as it was passed in by value.
        }

        /// <summary>
        /// this takes in a Reference type of Person, by reference
        /// </summary>
        /// <param name="person"></param>
        private static void PrintUserNameByRef(ref Person person)
        {
            Console.WriteLine(person.Name);
            person = null; //this has access to the orginonal reference, allowing us to alter it, either make it point to a different object or to nothing.
        }


    }

    class Person
    {
        public string Name { get; set; }
    }
}

If it java cannot do this, then its just passing a reference type by value? (is that fair to say)

Many thanks

Bones

© Stack Overflow or respective owner

Related posts about java

Related posts about parameters