I agree with the fact that the String objects are immutable, means they cannot be modified. Like in the case below
String str = "Hi";
String str1 = str.concat("Nilesh");
Here the str object will be returned if the length argument is 0 or a new String object will be created and its reference will be returned.
And if i do
String str = "Hi";
str="Hello";
How is it getting changed? where does immutable comes into picture? An example please.
What is immutable is the String itself, not the reference that points to the String. In your second code:
There are 2 String objects involved:
"hi"and"hello".stris a reference that originally points to the first one then points to the second one following an assignment. But the String object"hi"does not get modified in that code.