Concat() IN String:

Consider this example:
class demo
public static void main(String[] args){
String s=new String("hi");
s.concat(" bhabani");
The output is “ hi”. Not “hi bhabani”.
Actually what happens here,
Since Strings are immutable, the VM couldn't stuff this new value into the old String referenced by ‘s’, so it created a new String object, gave it the value "hi bhabani". Technically there are now three String objects,“hi”, “bhabani” and “hi bhabani”.
But ‘s’ still refers to “hi” not the new string object “hi bhabani”.
If we will write like this
Now it will give output “hi bhabani”.
Because here the new string reference is stored in 's'.The old string is still there.

No comments:

Post a Comment