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()?
Yes, pretty much. (though the JVM might do optimizations so that the same string literal used several times refers to the same String object).
Yes. As you say, everything is passed by value in Java, even references to object. So the variable
sinchangeIt( String s )is a different value fromstryou use in main(), it’s just a local variable within the changeIt method.Setting that reference to reference another object does not affect the caller of
changeIt.Note that the String object
srefer to is still the same String asstrrefers to when entering thechangeIt()method before you assign a different object tosThere’s another thing you need to be aware of, and that is that Strings are immutable. That means that no method you invoke on a string object will change that string. e.g. calling
s.toLowerCase()within your changeIt() method will not affect the caller either. That’s because the String.toLowerCase() does not alter the object, but rather returns a new String object.