I am wondering if it makes a difference if you pass an immutable type into a method in constrast to passing an mutable type into a method. I'm asking this because of the following code:
I have the following two methods, one taking a String (immutable) parameter and the other taking a StringBuilder (mutable) parameter:
static void change(String s) {
s = "!!!";
}
static void change(StringBuilder sb) {
sb.append("!!!");
}
Code for executing the code (with results written as comments):
public static void main(String[] args) {
String s = "Hello";
change(s);
System.out.println(s); //Prints Hello
StringBuilder sb = new StringBuilder("Hello");
change(sb);
System.out.println(sb); //Prints Hello!!!
}
The String object (immutable type) doesn't get changed by the method while the StringBuilder object (mutable type) gets changed by the method. Is this all the outcome of String being an immutable type and StringBuilder being an mutable type?
In both scenarios the reference/pointer is passed into the method right? Because the String object is immutable, it creates a new String and because the StringBuilder is mutable (and points to the same object), it changes the same StringBuilder right?