Question #72111

Explain what is difference between Pass-by-value and Pass-by-reference argument passing to a function .show the difference by example.

Expert's answer

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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS