permaculture playing cards*
The moose likes Beginning Java and the fly likes What do we mean by immutable? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What do we mean by immutable?" Watch "What do we mean by immutable?" New topic
Author

What do we mean by immutable?

raul saini
Greenhorn

Joined: May 18, 2010
Posts: 18
When we say arrays and Strings are immutable, what does it actually mean?

Thank You
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 31057
    
232

Immutable means the values in the object can't be changed after it is instantiated.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Tom Hass
Greenhorn

Joined: Jan 22, 2010
Posts: 5
raul saini wrote:When we say arrays and Strings are immutable, what does it actually mean?

Thank You


It means that they can't change their state after creation. Remember that Arrays and Strings are objects. A typical example would be 'String' (which is immutable) and 'StringBuffer or StringBuilder' (which are mutable).

Practical eg:

String s1 = "Joe";
String s2 = "Blog";

s1 += s2;

System.out.println(s1); // The s1 reference variable still retains its value as "Joe". In other to effectively add the s2 to s1, another String object needs to be created
//in other to effectively add the two objects together.

String s3 = s1 + s2; //which now contains the value: "Joe Blogs".

This is different to the other more specialised String classes such as StringBuilder and StringBuffer - which are mutable. (Use StringBuffer for Thread-safe operations).

Example:

StringBuilder sb = nee StringBuilder("Joe");

sb.append("Blogs"); // At this stage, the value of sb is "Joe Blogs".


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Welcome to the Ranch, Tom Hass
Tom Hass
Greenhorn

Joined: Jan 22, 2010
Posts: 5
Thanks Campbell. Obviously, my only post, can't be compared to your over 15,000 posts so far.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You're welcome

Of course about half my posts are "You're welcome" and "Welcome to the Ranch."
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3742
    
  16
raul saini wrote:When we say arrays and Strings are immutable, what does it actually mean?

Thank You


Nobody seems to have mentioned yet that arrays are not immutable. Their size can't be changed but their contents certainly can.


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What do we mean by immutable?