Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What do we mean by immutable?

 
raul saini
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we say arrays and Strings are immutable, what does it actually mean?

Thank You
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Immutable means the values in the object can't be changed after it is instantiated.
 
Tom Hass
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Tom Hass
 
Tom Hass
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell. Obviously, my only post, can't be compared to your over 15,000 posts so far.
 
Campbell Ritchie
Sheriff
Posts: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome

Of course about half my posts are "You're welcome" and "Welcome to the Ranch."
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic