String Immutable

  1. Why strings are immutable and string builder is not?

  2. Garbage collector?

Since String is immutable in Java, whenever we do String manipulation like concatenation, substring, etc. it generates a new String and discards the older String for garbage collection.

These are heavy operations and generate a lot of garbage in heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation.

StringBuffer and StringBuilder are mutable objects in Java. They provide append(), insert(), delete(), and substring() methods for String manipulation.

see this:
https://www.geeksforgeeks.org/garbage-collection-java/#:~:text=Garbage%20collector%20is%20best%20example,memory%20by%20destroying%20unreachable%20objects.

Still it does not answered about why string is immutable in java