Java Immutable Explained. Immutable Objects With Examples.

What This Article About

Immutability is a broad concept and has many angles. Immutability is a set of practices that potentially might reduce the number of bugs in your application. As a consequence, this subject invokes confusion. Here, we review it from a different perspective. I'll explain the most important immutability aspects in clear language.

Mutability Problems Examples

Before we start, let's review two examples. They are pretty artificial but explain potential problems with mutable code:

Immutability in JavaScript — When and Why Should You Use It

The concept of immutability is nothing new because it’s been around for a long time in functional and object-oriented programming languages. The idea wasn’t much prevalent in JavaScript, but it has slowly grown into the programming community recently. React is a strong proponent of keeping the state immutable and Facebook has contributed a library called Immutable.js to help this cause.

In this tutorial, we’ll answer the following questions:

JSON Values and the Joy of Scala

One of the most important aspects of functional programming is immutable data structures, better known as values. Updating these structures using the copy-on-write approach is very inefficient, and this is the reason why persistent data structures were created. 

On the other hand, JSON is a lightweight, text-based, language-independent data interchange format. It's become so popular due to its simplicity. There are a lot of libraries out there to work with JSON in the JVM ecosystem; however, none of them use persistent data structures.

Java SimpleDateFormat Is Not Simple

Formatting and parsing dates is a daily (painful) task. Every day, it gives us another headache.

A common way to format and parse dates in Java is using SimpleDateFormat. Here is a common class we can use.

Immutable Data Structures in Java

As part of some of the coding interviews I’ve been conducting recently, the topic of immutability sometimes comes up. I’m not overly dogmatic in it myself, but whenever there’s no need for mutable state, I try to get rid of code which makes code mutable, which is often most visible in data structures. However, there seems to be a bit of a misunderstanding on the concept of immutability, where developers often believe that having a final reference, or val in Kotlin or Scala, is enough to make an object immutable. This blogpost dives a bit deeper in immutable references and immutable data structures.

Benefits of Immutable Data Structures

Immutable data structures have significant benefits, such as: