Why we can't add character at certain position by charAt(index) in java

Viewed 620
public class ReverseString {
    public static void main(String[] args) {
        String s = "mnop";
        s.charAt(0) = 'l';
    }
}
4 Answers

Java only allows you to assign to variables, fields and array elements.

The result of a method - like s.charAt(0) - is none of these, so you can't assign to it.

The reason for this is down to the way Java returns: it returns by value, not by reference, and that value only exists temporarily. As such, if you were able to assign it, the side effect of that assignment is immediately lost, making it pointless.

It's also true that String is immutable; but this limitation on what you can assign to is the reason you couldn't do this even for some notional MutableString class you might try to create.

Strings in java are immutable, meaning they can't change at all.

To do something like this, use a StringBuilder:

StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');

//later, you probably want to get back to a String:
String s = sb.toString();

s.charAt(0) returns a char value, not a char variable to which you could assign a value.

And anyway, String is immutable, so you can't modify the value of an existing String.

You can obtain a copy of the array of all the characters of the String, and modify that array:

String s = "mnop";
char[] chars = s.toCharArray();
chars[0]= 'l';

However, this doesn't modify the original String, since it's immutable.

You can create a new String using that array though:

String newS = new String(chars);

charAt returns a char that's a copy of the character at that position in the string. It's not a reference back to the original string, which is immutable.

You could use a StringBuilder instead, though:

StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');
String s = sb.toString();
Related