It is often the case that programmers would want to manipulate String objects. The way String objects in java work is that it creates a new object every time a String is manipulated. This is very time consuming. I know there is a Stringbuffer class that allows for mutable strings but I am trying to understand why Java suggests that Strings should be immutable? and is this a common thing among other programming/scripting languages as well?
Asked
Active
Viewed 272 times
-1
-
2http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/ – OldProgrammer Nov 16 '14 at 01:11
-
1Keeto - please look for related questions and answers before you ask questions. As you can see, this particular one has been asked and answered a number of times previously. – Stephen C Nov 16 '14 at 02:16
-
Keeto - if you feel that your question warrants asking anyway, please make sure that you say clearly what is *different* about your question. Note that *"I did not like / understand / believe the answers"* is not a justification to ask a duplicate question. If you want a BETTER answer, offer a bonus on an existing question. – Stephen C Nov 16 '14 at 02:20
2 Answers
5
Here is a nice article on the advantages of using immutable object in general http://www.javapractices.com/topic/TopicAction.do?Id=29
Benefits of using immutable object:
- are simple to construct, test, and use
- are automatically thread-safe and have no synchronization issues
- don't need a copy constructor
- don't need an implementation of clone
- allow hashCode to use lazy initialization, and to cache its return value
- don't need to be copied defensively when used as a field
- make good Map keys and Set elements (these objects must not change state while in the collection)
- have their class invariant established once upon construction, and it never needs to be checked again
- always have "failure atomicity" (a term used by Joshua Bloch): if an immutable object throws an exception, it's never left in an undesirable or indeterminate state

Ryan Hartman
- 191
- 4
0
In languages immutability has several useful advantages. They can be freely shared; no copying overhead, etc. An immutable object has exactly one state. Many other languages (such as Python, C#) use immutable strings.

seand
- 5,168
- 1
- 24
- 37