Yes, this is a basic point of confusion that has been discussed before, but there's a lot of convoluted information and I'm hoping that someone can pinpoint my exact misunderstanding here.
public class Test {
public static void change(int i) {
i = 2;
}
public static void change(int[] i) {
i[0] = 6;
}
public static void change(String i) {
i = "Bye";
}
public static void main(String[] args) {
int a = 1;
int[] b = {3,4,5};
String c = "Hello";
change(a);
change(b);
change(c);
System.out.println(a); // 1 - value unchanged
System.out.println(b[0]); // 6 - value changed
System.out.println(c); // Hello - value unchanged
}
}
- The variable
a
actually contains the value 1. When we pass this to thechange()
method, a new variable is created, which also contains the value 1. Thus when we changei
,a
is unaffected. This makes sense. - The variable
c
contains a reference to an array object in memory. When we pass this to thechange()
method, a new variable is created, which contains the same reference. Thus, they both represent the same object. So when we changei[0]
,c[0]
is also changed. This also makes sense. - What I'm having trouble with is if Strings are just object references in Java, why do they behave like primitives in this regard?