I am confused about the pass-by-value mechanism in Java even though I have read some questions about it like this and this.
I thought primitive type is passed by value in function parameters so it won't change its value even though it is changed in the function scope.
public class A {
void function(int i) {
i = 3;
}
public static void main(String[] args) {
int i = 2;
function(i);
System.out.println(i); // variable `i` won't change
}
}
But class object is passed by value of a reference in function parameters so it will change its value if it is changed in the function scope.
public class Obj{
public double calPrice;
public boolean isTop;
public boolean isCate;
public List<Integer> cList;
public RPCRecord(double c, boolean iT, boolean iC, List<Integer> cL) {
calPrice = c;
isTop = iT;
isCate = iC;
cList = cL;
}
}
void f2(Obj o) {
List<Integer> l1 = new ArrayList<Integer>(){{
add(1);
add(2);
add(3);
}};
Obj o2 = new Obj(10.0, true, false, l1);
o = o2;
}
void f3(Obj obj) {
obj.calPrice = 123123.1;
obj.isTop = false;
obj.add(10);
}
public class A {
public static void main(String[] args) {
Obj ojb = new Obj();
f2(ojb);
System.out.println(ojb); // Object `obj` will change
f3(ojb);
System.out.println(ojb); // Object `obj` will change
}
}
Forgive that I am not familiar enough with the Java pass parameter mechanism.
Is that what I thought right?