Skip to main content

Understanding Immutability in Java: Strings and Other Immutable Objects

In the Java programming language, an object is considered immutable if its state cannot be changed after it is created. Immutable objects are useful for several reasons, including thread safety, security, and ease of reasoning about code. In this blog post, we will discuss immutability in Java and focus on two examples of immutable objects: strings and wrapper classes.

Strings

Strings are perhaps the most well-known example of immutable objects in Java. Once a string object is created, its value cannot be changed. This is because strings are implemented as an array of characters, and the contents of an array cannot be changed after it is created. Here is an example to illustrate this:

String s = "hello";
s.toUpperCase(); // returns "HELLO"
System.out.println(s); // prints "hello"

In this example, the "toUpperCase" method returns a new string object with all of the characters in uppercase. However, the original string object "s" remains unchanged. This is because the "toUpperCase" method does not modify the existing string object, but rather creates a new one.

Wrapper Classes

Wrapper classes are another example of immutable objects in Java. Wrapper classes are used to represent primitive data types (such as int, double, and boolean) as objects. For example, the "Integer" wrapper class is used to represent integer values as objects. Once an object of a wrapper class is created, its value cannot be changed. Here is an example:

Integer i = 5;
i++; // i is now 6
System.out.println(i); // prints 6

In this example, the "++" operator increments the value of "i" by 1. However, because "i" is an object of the "Integer" wrapper class, a new object is created with the value of 6. The original object with the value of 5 is discarded.

Other Examples of Immutable Objects

There are several other examples of immutable objects in Java, including:

  • The "BigDecimal" class, which is used to represent arbitrary-precision decimal numbers
  • The "LocalDate" and "LocalTime" classes, which are used to represent dates and times without time zone information
  • The "Duration" and "Period" classes, which are used to represent time spans and periods of time, respectively

Conclusion

Understanding immutability in Java is important for writing code that is thread-safe, secure, and easy to reason about. In this blog post, we discussed two examples of immutable objects in Java (strings and wrapper classes) and highlighted several other examples. We hope this blog post has been helpful in understanding the concept of immutability in Java and its practical applications. By using immutable objects, you can ensure that your code is more robust and easier to maintain.

Comments