"Java is pass-by-value
"
-Java Language Specification
However, there are things that confuses me. Please take a glimpse of my example
public class Main {
public static void main(String[] args) {
StringBuilder myBuilder = new StringBuilder("Michael");
editString(myBuilder);
System.out.println(myBuilder);
}
public static void editString(StringBuilder x){
x.append(" Ardan");
}
}
Output:
Michael Ardan
And this example:
public class Main {
public static void main(String[] args) {
int myInt = 10;
editInt(myInt);
System.out.println(myInt);
}
public static void editInt(int x){
x ++;
}
}
Output:
10
I tried reading other articles and it all says that Java is always pass-by-value
. I've done some test scenario. Comparing both example to each other made me think that Java's Objects are pass-by-reference
and primitive types are pass-by-value
. However, if you tried to replace the int
primitive type into Integer
Object, the result would be the same. I would love if somebody explain these two examples here.