Back OCAJP
When primitive values are passed into methods, a copy is passed in. The copy of the primitive can changes value inside the method body, the original copy won't be effected.
When an object reference is passed into method, a pointer to the reference is passed in. The object can be changed via the object reference regardless inside or outside of method body.
OCAJP>cat test.java
class test{
public static void main(String...args) {
test t = new test();
int a = 1;
t.passCopy(a);
System.out.println(a); //original a didn't change value
String b = "String-outside";
System.out.println(t.passCopy2(b));
System.out.println(b); //original b didn't change value
StringBuilder sb = new StringBuilder("StringBuilder-outside");
t.passRef(sb);
System.out.println(sb);
}
void passCopy(int a) {
a = 10;
}
String passCopy2(String b) {
b = "String-inside";
return b;
}
void passRef(StringBuilder sb) {
sb.append("StringBuilder-inside");
}
}
OCAJP>javac test.java
OCAJP>java test
1
String-inside
String-outside
StringBuilder-outsideStringBuilder-inside
Back OCAJP