Studying for OCAJ7
I know String objects are immutable. I know using methods like .concat() on a String object will just create a new String object with the same reference name. I'm having a hard time, however, with wrapping my head around the following:
String str1 = "str1";
String str2 = "str2";
System.out.println( str1.concat(str2) );
System.out.println(str1);
// ouputs
// str1str2
// str1
String str3 = "fish";
str3 += "toad";
System.out.println(str3);
// outputs
// fishtoad
If strings are immutable, why does using += to concatenate affect the original String object, but .concat() does not? If I only want a String to concatenate with using +=, is using String better than using StringBuilder, or vice versa?
concatdoesn't assign the result of the concatenation tostr1, it returns it.char[]and you can't just add more elements to an array), how canstr3be changed using+=?+=creates a new instance of a String, which contains the concatenation of the 2 strings, and gives the reference tostr3.str3 += "toad"replaces the original stringstr3of "fish" with "fishtoad". concat() returns a new instance, sostr3 += "toad"is similar tostr3 = str3.concat("toad");