Can you pass by reference in Java?
- by dbones
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