0

In the below program, I'm trying to replace a string and trying to assign it to the same variable. But in Java, the Strings are immutable. So once created, we cannot able to modify it. But here I can be able to modify. Not sure whether my understanding is correct. Can anyone help me?

public static void main(String[] args) {

        String s = "1234504";
         s = s.replaceAll("0", "");
        int count = 0;
        for(int i = 0; i< s.length() ; i++){
            if(Character.isDigit(s.charAt(0))){
                count++;
            }
        }
        System.out.println("Number of digits in string");
        System.out.println(count);

    }
2
  • 2
    You're not modifying the string, you're replacing it with a new one. Commented May 16, 2017 at 10:10
  • Not related to question but: since you are replacing literals you don't need to call replaceAll which support regex. It is better to call replace instead since you are safer to not face problems when your literal will contain regex metacharacters like + * ^ $ and others. Both methods will replace all occurrences of searched part in string. Only difference between these methods is regex support. Commented May 16, 2017 at 10:22

1 Answer 1

0

s = s.replaceAll("0", ""); doesn't mutate a String, it creates a new String and assigns it to the s variable. The original String that was referenced by s remains unchanged.

Sign up to request clarification or add additional context in comments.

5 Comments

Could you please give me an example for mutating a string
@Aishu No, because you can't mutate a String.
We can't be able to modify a string which is defined as final rt... Is that also an example that we can't be able to mutate a string. Am I right?
@Aishu No, that's just an example that you can't assign a new value to a final variable (and it doesn't matter if the object referenced by that variable is mutable or not).
@Aishu You need to understand difference between object and variable. Immutability is about object, not variable which holds reference to it. Lets say you have cat sculpture. You can't change it into dog sculpture (especially if dog is bigger), but you can buy new dog sculpture and replace cat with dog. So sculpture is still immutable, but place where you want to hold sculpture is not. It is same about object and variable. Immutability is object property, not variable which holds it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.