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?
-
2programcreek.com/2013/04/why-string-is-immutable-in-javaOldProgrammer– OldProgrammer2014-11-16 01:11:19 +00:00Commented Nov 16, 2014 at 1: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– Stephen C2014-11-16 02:16:52 +00:00Commented Nov 16, 2014 at 2: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– Stephen C2014-11-16 02:20:46 +00:00Commented Nov 16, 2014 at 2:20
Add a comment
|
2 Answers
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
1 Comment
Ben
And also yes, it is very common