/*Java is Pass-by-Value
Pass-by-value
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application.
Pass-by-reference
The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.
Java is strictly pass-by-value
Litmus test is swap method.
Value outside the method not changed.
*/
public class Swap {
public static void main(String [] args)
{
int a=20;
int b=30;
swap(20,30);
System.out.println(" "+a+" "+b);
}
public static void swap(int a,int b)
{
// int temp=a;
// a=b;
// b=temp;
a=a+b;
b=a-b;
a=a-b;
System.out.println(" "+a+" "+b);
}
}
Another good example show how values change if you directly change value pointed by that reference else if you create by new operator or setters, it will not change.
public class PassByRefEx {
public static void main(String [] args)
{
int [] a={2,3,6,9,10};
int abc=23;
Dog aDog = new Dog("Max");
System.out.println("int Before modification "+abc);
System.out.println("Dog object Before modification "+aDog.name);
System.out.print("Array Before modification ");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
modifyArray(a,abc,aDog);
System.out.println("int After modification "+abc);
System.out.println("Dog object after modification "+aDog.name);
System.out.print("Array After modification ");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
public static void modifyArray(int []b, int x, Dog d)
{
// d.setName("Fifi"); // would change the name of the dog
d = new Dog("Fifi"); // would not change the original variable
// b[0] = 3; // would change the contents of the original array
b = new int[1]; // followed by...
b[0] = 3; // would not affect the original array
x=34; // It would not affect the original value
}
}
class Dog {
String name=null;
public Dog(String aname)
{
name=aname;
}
public void setName(String bname)
{
name=bname;
}
}
No comments:
Post a Comment