Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Immutable objects are objects that can't be changed programmatically. They're especially good for multi-threaded environments or other environments where more than one process is able to alter (mutate) the values in an object.</p> <p>Just to clarify, however, StringBuilder is actually a mutable object, not an immutable one. A regular java String is immutable (meaning that once it's been created you cannot change the underlying string without changing the object).</p> <p>For example, let's say that I have a class called ColoredString that has a String value and a String color:</p> <pre><code>public class ColoredString { private String color; private String string; public ColoredString(String color, String string) { this.color = color; this.string = string; } public String getColor() { return this.color; } public String getString() { return this.string; } public void setColor(String newColor) { this.color = newColor; } } </code></pre> <p>In this example, the ColoredString is said to be mutable because you can change (mutate) one of its key properties without creating a new ColoredString class. The reason why this may be bad is, for example, let's say you have a GUI application which has multiple threads and you are using ColoredStrings to print data to the window. If you have an instance of ColoredString which was created as</p> <pre><code>new ColoredString("Blue", "This is a blue string!"); </code></pre> <p>Then you would expect the string to always be "Blue". If another thread, however, got ahold of this instance and called</p> <pre><code>blueString.setColor("Red"); </code></pre> <p>You would suddenly, and probably unexpectedly, now have a "Red" string when you wanted a "Blue" one. Because of this, immutable objects are almost always preferred when passing instances of objects around. When you have a case where mutable objects are really necessary, then you would typically guard the objet by only passing copies out from your specific field of control.</p> <p>To recap, in Java, java.lang.String is an immutable object (it <em>cannot</em> be changed once it's created) and java.lang.StringBuilder is a mutable object because it can be changed without creating a new instance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload