Call_By_Value OR Call_By_Reference:
In general, there are two ways that a computer language can pass an argument to a subroutine. The first way is call-by-value. This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. The second way an argument can be passed is call-by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine. As you will see, Java uses both approaches, depending upon what is passed.
When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object that its corresponding argument does.
When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.
Example
Returning and Passing Objects to Methods:
class Box
{ int height, width;
Box(int boxHeight,int boxWidth)
{
height = boxHeight;
width = boxWidth;
}
void showboxHeightWidth()
{
System.out.println("Height = " + height);
System.out.println("Width = " + width);
}
Box changeBox(Box objBox) //Object as return type and as parameter
{
objBox.height = 7;
objBox.width = 9;
return objBox;
}
public static void main(String args[])
{
Box myBox = new Box(3,5); //Create myBox object
System.out.println("Before Change");
myBox.showboxHeightWidth(); //print myBox
myBox = myBox.changeBox(myBox); //myBox is given to method for change
System.out.println("After Change");
myBox.showboxHeightWidth();
}
}
Post a Comment
Post a Comment
Please do not enter any spam link in the comment box