Monday 17 June 2019

immutability - Why string is called immutable in java?





I understand that Immutable objects are objects that cannot be modified. But string can be modified when we use functions. So how do we say string are immutable? this was a question asked interview. Need answer asap


Answer




But string can be modified when we use functions.





No, what you get back is a different string. Example:



String a, b, c;

a = "testing 1 2 3";
b = a.substring(0, 7); // Creates new string for `b`, does NOT modify `a`
c = a.substring(8);

System.out.println(b); // "testing"

System.out.println(c); // "1 2 3", proves that `a` was not modified when we created `b`


As you can see, the string "testing 1 2 3" was not modified by the substring call; instead, we got back a new string with just "testing".



String objects are immutable in Java because they provide no methods that modify the state of an existing String object. They only provide methods that create new String objects based on the content of existing ones.



(The above is, of course, unless you play very naughty games indeed with reflection.)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...