Answer on Question #72111 - Programming & Computer Science / Java | JSP | JSF
Question
Explain what is difference between Pass-by-value and Pass-by-reference argument passing to a function .show the difference by example.
Answer
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value.
Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.
Example 1(Pass by Value)
public class MathFunction{
public static void main(String[] args) {
int original = 10;
System.out.print("Original before: " + original);
System.out.println();
incrementValue(original);
System.out.println("Original after: " + original);
}
static void incrementValue(int inFunction){
inFunction++;
System.out.println("In function: " + inFunction);
}
}Example 1(Pass by Reference)
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
}
Reference: https://stackoverflow.com
Answer provided by https://www.AssignmentExpert.com