Immutability

Strings

Immutability

🙋 Need help? Ask an expert now!

String objects are designed to be immutable. There is no way to alter or manipulate their data once the object is created. Although you cannot change a String, you are able to reassign its references. Let's take a look below to see how this works.

ImmutabilityExample.java
package exlcode;

public class ImmutabilityExample {

  // exampleVariableOne holds the reference to the String "Hello World!"
  public static String exampleVariableOne = "Hello World!";

  public static void main(String[] args) {
    // the String reference for exampleVariableOne changes to the String "Java"
    exampleVariableOne = "Java";
    System.out.println(exampleVariableOne);
  }
}

We can assign exampleVariableOne to a new String object ("Java") before it is printed. However, the old String object ("HelloWorld") still exists because it cannot be changed. The reassignment of a variable does not replace the old string with the new one as it only replaces the reference. This means that both strings still exist but only one of them is being used.

Take a look at this line of code: String varOne = "Hi"; Let's revisit the concept. The reference variable varOne does not contain the object, but only a reference to the object. What this reference is and what object it points to can change at anytime in the program. But the String object "Hi" remains unaltered because it is immutable.

On a side-note, constantly creating "Strings" could lead to overflowing the memory when running the code.

Edit Me on GitHub!

Application Question

Which of the following statements are CORRECT?