File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mutable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mutable" Watch "Mutable" New topic


NDP Prasad
Ranch Hand

Joined: Apr 13, 2006
Posts: 177
What is mutable and immutable? why string objects are called immutable?

Swami Vidhyananda

Joined: Apr 06, 2006
Posts: 6

Refering to,

Mutable means - That which is capable or subject to change or alteration.

A String in Java is atomic It cannot be changed. Once a String object is created on the heap, the literals (alphabets of the String) cannot be changed.

String s = "Sun";

String class does not have any methods to modify "Sun" to "Son"

To modify a String , you have to push the contents to a StringBuffer and then modify. The resultant is a NEW STRING object. However the source string remains untouched.


Maneessh saxena
Ranch Hand

Joined: Oct 03, 2006
Posts: 125
Immutable means " Once you have assigned a String a value, that value can never change "— it's immutable,
frozen solid.while the String object is immutable, its reference variable is not means it can refer to another String object if it's diected to refer another String object leaving previous String object unchanged.

String s = "abcdef"; // create a new String object, with
// value "abcdef", refer s to it

String s2 = s; // create a 2nd reference variable
// referring to the same String

// create a new String object, with value "abcdef more stuff",
// refer s to it. (Change s's reference from the old String
// to the new String.) ( Remember s2 is still referring to
// the original "abcdef" String.)

s = s.concat(" more stuff");

The main advantage of String object's immutability is that there may be many references to single String object
and if any reference changes the String object it'll reflect to all other references,which is not a good idea so in case any referense changes contents of String object a new String object is created and reference is directed to newly created String.

i hope this will help you..


SCJP 1.4, SCWCD 1.5
I agree. Here's the link:
subject: Mutable
It's not a secret anymore!