If Strings are Objects (and they are) then why...
Consider this block of code below:
Author tolkein = new Author("J.R.R.", "Tolkein"); changeAuthor(tolkein); System.out.println(tolkein.getLastName()); String quote = "One Ring to Rule Them All"; changeQuote(quote); System.out.println(quote);
and the following methods:
static void changeAuthor(Author author) { author.setLastName("Anthony"); }
static void changeQuote(String quotation) { quotation = "A wizard is never late. Nor is he early. He arrives precisely when he means to."; }
The output would read
One Ring to Rule Them All AnthonyKnowing that objects in Java are passed by reference, it makes sense that Tolkein's last name would change to "Anthony." But aren't Strings also Java objects? (yes!) Then why wouldn't our Lord of the Rings quote change after invoking the changeQuote() method?
This has to do with the immutability of Strings in Java. Simply put, once a string is created, it cannot be changed. The Java documentation states the following:
The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods ... that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
Since strings are immutable, when the changeQuote() method is invoked, at attempt is made to "change" the string quotation. What actually happens is that a new string is created that reminds us that wizards are never late. This new string only has scope visiblity inside the changeQuote() method. Once that method completes, there is no longer a way for us to access the new String that Java created for us.