Why is Immutability matters ?

Shanira Perera
2 min readAug 21, 2022

--

Hi all, welcome to another techie talk….

What is Immutability means

We can simply says immutable is once we create an object we cant change or modify it. but we try to modify is it creates another new object.

lets take an example to understand this more clearly

  • String name =“Peter”;

In java if we create an object they stored in the Heap and point the name variable to the Peter. think if we create another object called “Jane” what it happens is name variable de-referencing from the Peter and points to the Jane. that means in java design String is immutable OK, lets talk why its immutable,

  • String name = “Peter”
  • String student = “Peter”
  • String employee = “Peter”

In this situation java acts like this, it creates different variables but points to one object. so that we can get an idea about the immutable advantage. peter is a 4 bit value so in this three variables also has same value of peter then jvm no no need more space to store same value its create one object and assign it to there in that case lots of memory space was saved. but if we create like this,

  • String employee = new String(“Peter”)

This not equal to the name because this peter is create in another memory address.

Ok lets look another example,

  • String name = “Peter”
  • String name = “Saman”

In this situation what happened is first java reference the name as peter after that it de-reference it and assigned the saman as new object.

if java String is not immutable saman can acts like peter. thats mean its going to be a huge problem.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shanira Perera
Shanira Perera

Written by Shanira Perera

Hello, I’m Shanira, welcome to the world of technology. I am an Associate software engineer at virtusa. So let’s begin!

No responses yet