I am reading about Pass by Value and Pass by reference in java, I got many articles,some of them saying Java is following only ‘Pass by value ” and some of them saying some difference between primitive and object. so I wrote following sample code.
and putting output also.
Please comment and share what is exactly the answer is.
I checked for Int, String , StringBuffer and Employee class, now Its working as pass by reference for Employee class only.
package test;
class Emp {
public String name="";
public int age=0;
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Name: "+ this.name + "....Age: "+ this.age;
}
}
public class Class1 {
public Class1() {
super();
}
public void doChange(int i) {
i = i +10;
System.out.println("Value of Integer in Method:>"+ i);
}
public void doChange(Emp i) {
i.age=29;
i.name="rishu";
System.out.println("Value of Employee In Method "+i.toString());
}
public void doChange(String i) {
i = i + " Hello";
System.out.println("value of i->"+ i);
}
public static void main(String[] args) {
int i =10;
String str="XXX";
Class1 c= new Class1();
StringBuffer sb= new StringBuffer();
Emp e= new Emp("abhi",28);
sb.append("ABC ");
System.out.println("");
System.out.println("Value of Integer before Method:->"+ i);
c.doChange(i);
System.out.println("Value of Integer after Method:->"+ i);
System.out.println("");
System.out.println("Value of String before Method:->"+ str);
c.doChange(str);
System.out.println("Value of Integer after Method:->"+ str);
System.out.println("");
System.out.println("Value of StringBuffer before Method:->"+ sb);
c.doChange(sb.toString());
System.out.println("Value of StringBuffer after Method:->"+ sb);
System.out.println("");
System.out.println("Value of Employee before Method:->"+ e.toString());
c.doChange(e);
System.out.println("Value of Employee after Method:->"+ e.toString());
}
}
Output:
Value of Integer before Method:->10
Value of Integer in Method:>20
Value of Integer after Method:->10
Value of String before Method:->XXX
value of i->XXX Hello
Value of Integer after Method:->XXX
Value of StringBuffer before Method:->ABC
value of i->ABC Hello
Value of StringBuffer after Method:->ABC
Value of Employee before Method:->Name: abhi....Age: 28
Value of Employee In Method Name: rishu....Age: 29
Value of Employee after Method:->Name: rishu....Age: 29
Java is pass-by-value only.
However, for objects, what is passed by value is a reference to the object. No, that’s not the same as pass-by-reference. The difference is this:
If in you do this:
It has absolutely no effect outside the method – because the reference
iis a copy of the reference used outside the method. However, it refers to the same object, so if you use the reference to change fields of the object, these changes are visible outside the method.