I am confused why in the first code (Code 1), the object pointed to by myCounter was updated to the value 2 after passing to the method "print". But in the second code (Code 2), the object pointed to by str is still the same literal "This is a string literal." I thought the str (the str is an object reference just like myCounter I think) experience the same mechanism since it is also passed to a method, so shouldn't it get updated just like myCounter?
This is code 1:
public class PrimitiveVsReference{
private static class Counter {
private int count;
public void advance(int number) {
count += number;
}
public int getCount() {
return count;
}
}
public static void main(String args[]) {
int i = 30;
System.out.println("value of i before passing to method : " + i);
print(30);
System.out.println("value of i after passing to method : " + i);
Counter myCounter = new Counter();
System.out.println("counter before passing to method : " + myCounter.getCount());// this gives 0
print(myCounter);
System.out.println("counter after passing to method : " + myCounter.getCount());// now this gives 2 after passing into the method "print"
}
/*
* print given reference variable's value
*/
public static void print(Counter ctr) {
ctr.advance(2);
}
/**
* print given primitive value
*/
public static void print(int value) {
value++;
}
}
Code 2:
String str = "This is a string literal.";
public static void tryString(String s)
{
s = "a different string";
}
tryString(str); // isn't this here doing the samething as when myCounter is passed to print in Code 1?
System.out.println("str = " + str); // But this here output the original literal "This is a string literal."
Could someone explains what is going on?