This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Ok, so i know the rules about passing a primitive and an object refernce to a method. But str is a reference to a String object, so wouldn't line 2 modify the state of the object refered to by str at line one. Or does get treated like a literal value?
Strings are immutable; you can't change their value. Your code doesn't modify any strings - it creates a new one and returns it. Don't let the name of your argument confuse you. Your code is the same as...
As I understand Strings being immutable means I cannot change what is stored in them. Like example from str = "Rich" to str = "RICH" is not possible. (Got this example from a book). But this program shows otherwise changing the string. ( I am surely missing something)
Strings are immutable, they cannot be changed. Their reference variables on the other hand are not immutable, they are weak and open to negotiation.
str = "String Changed"; //Line 2 accessing global str
This line did not actually change the String object referenced by str, it created a completly new String object gave it the value "String Changed" and then told str to reference the new String object. The old string object "My String OBJECT" still exists still exists on the heap but now nothing is referencing it so it becomes available for garbage collection.