In the case of Arraylist string objects the added elements are getting retrived. In case of String the method call has no effect on the String being passed.
It happens cause Java is Pass-by-Value and String
s are immutable
When you call
markAsNull(ArrayList<String> str)
The a new reference by name str
is created for the same ArrayList
pointed by al
. When you add
an element on str
it gets added to same object. Later you put str
to null
but the object has the new values added and is pointed by a1
.
When you call
markStringAsNull(String str)
{
str = str + "Append me";
// ...
}
The line str = str + "Append me";
creates a new String
object by appending the given string and assignes it to str
. but again it is just reference to actual string which now pointing to newly created string. (due to immutablity) and the original string is not changed.