-3

What is the difference between

str.replaceAll(); //1

and

str = str.replaceAll(); //2

When I try the first one the compiler doesn't give error but the string is not changed at all but the second one works fine. What does the first one do? Sample code below:

    String str = "abcdefgh";
    str.replaceAll("abcd", ""); //1st replacement
    System.out.println(str);
    str = str.replaceAll("abcd", ""); //2nd replacement
    System.out.println(str); 

The output after 1st one is

abcdefgh

and after the second one is

efgh

I know we should use second one because it updates but still aren't String objects? We are like calling the replaceAll() method for it and it should change it but why it doesn't? Any ideas would be much appreciated.

dev1ce
  • 101
  • 3
  • 11

2 Answers2

5

str.replaceAll("abcd", "") doesn't modify the source String, since Strings are immutable. Instead, it creates a new String and returns it. That's the reason you have to assign the returned String back to str.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

The difference is the same as for i + 3; and i = i + 3. The first one does something and basically throws away the result. The second one store the result in the variable.

PendingValue
  • 252
  • 1
  • 12
  • but sir i + 3; gives error but str.replaceAll() doesn't. Why would the compiler generate useless result and throw it away? – dev1ce Apr 14 '16 at 11:50
  • @Geek The compiler would probably not do that, but you're asking it to – Oskar Kjellin Apr 14 '16 at 11:51
  • Yes, the compiler wouldn't take just this statement, but I thought it will get the idea across. The thing is that you call a method on the String. As other people mentioned here already, Strings are immutable (meaning, they can not be changed). Your method would create a new String but it is not stored in any variable yet. To store the result, you would need to do the `str = /**/` part. – PendingValue Apr 14 '16 at 11:58
  • That's because `i + 3` is an expression, whereas `str.replaceAll(...)` is both an expression and a statement, because it is invoking a method on an instance. – Andy Turner Apr 14 '16 at 11:59