I know that in Java, everything is passed by value. But for objects, it is the value of the reference to the object that is passed. This means that sometimes an object can get changed through a parameter, which is why, I guess, people say, Never modify parameters.
But in the following code, something different happens. s
in changeIt()
doesn't change when you get back to main()
:
public class TestClass {
static String str = "Hello World";
public static void changeIt( String s ) {
s = "Good bye world";
}
public static void main( String[] args ) {
changeIt( str );
System.out.println( str );
}
}
I'm guessing -- and I'd like confirmation -- that when you say s = "something"
it's the same or equivalent to saying String s = new String("something")
. Is this why s
doesn't change? Is it assigned a whole new object locally which gets thrown away once you exit changeIt()
?