Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Immutability
Java String Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java String Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java Strings.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.