pass by reference in java

In java there is no pointer concepts. So pass by reference using pointer is not possible in java. In java pass by reference is achieved by passing objects as arguments. It is possible to pass objects as argument to a function in java. In this post i am going to explain how to pass an object as reference in java.
Ads by Google


For better understanding consider the code segment given bellow. 
      class TestClass  
{
String msg;
public TestClass(String msg)
{
this.msg = msg;
}
public boolean checkObject(TestClass obj)
{
if(obj.msg.equals(msg))
return true;
else
return false;
}
}
public class ObjectPassing
{
public static void main(String args[])
{
TestClass test1 = new TestClass("Apple");
TestClass test2 = new TestClass("Orange");
TestClass test3 = new TestClass("Apple");
System.out.println("test1 = test2 :"+test1.checkObject(test2));
System.out.println("test1 = test3 :"+test1.checkObject(test3));
}
}

In this example the TestClass contain a method called checkObject, which accept an object as argument. Here you can see that the type of the argument is the name of the class.
     public boolean checkObject(TestClass obj)  
{
if(obj.msg.equals(msg))
return true;
else
return false;
}

Here we check the value of the variable "msg" for the three objects test1, test2 and test3. In this method if the value of the variable "msg" corresponding  to the two objects is found to be true, then it return true otherwise false.
Here is the output of the program.



Constructor Overloading                                        Index