DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Trending

  • Memory Optimization and Utilization in Java 25 LTS: Practical Best Practices
  • Microservice Architecture and Design Patterns for Microservices
  • Service Mesh Unleashed: A Riveting Dive Into the Istio Framework
  • A Framework for Securing Open-Source Observability at the Edge

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. String: Why it Is Immutable?

String: Why it Is Immutable?

Want to learn more about why String is immutable? Check out this post where we take a look at Strings and what it means to be immutable.

By 
Nitin Ranjan
·
Updated Oct. 30, 18 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
56.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Why String Is Immutable?

This is one of the most popular interview questions. In this blog, we are going to talk about it and help you find the answer. String is one of the most used classes in any application. For storing the username, password, address, IP address, etc., we need to create String objects. So, it is necessary to understand why our most famous and used class is immutable.

First of all, let’s see what immutable means:

Meaning of Immutable

"not changing or unable to be changed"

In the object-oriented world, immutable objects mean that once the constructor for an object has completed its execution, that instance can’t be altered.

In languages like Java and C#, the String object is immutable.

Why String Is Immutable?

In Java, String is a final and immutable class, which makes it the most special. It cannot be inherited, and once created, we can not alter the object. String object is one of the most-used objects in any of the programs.

Let’s talk about some String features and what will help us to understand why String is immutable:

ClassLoader

A String is used as an argument for class loading. Let’s imagine what will happen if String is mutable. In that case, the value of the object can be changed and wrong class can be loaded.

Immutability provides security so that the correct class is getting loaded by the Classloader. For example, we want to load the com.generic.class.PasswordChecker class to verify the user password, but perhaps, the referenced value can be changed to com.hacked.PasswordChacker.

Thread Safe

Immutability implicitly makes the String thread safe. A single String instance can be shared across threads. We don’t have to use synchronization for thread safety.

Security

In class loading, we have seen how String immutability helps in loading the correct class and provides security. There are other examples where String immutability helps in gaining security. 

For example, in a banking application, the username, password, bank account details, etc. are passed as the String. As String is immutable, its value can’t be changed. Otherwise, any hacker could change the referenced value to cause security issues.

Perfect Candidate for HashMap Key

String is mostly used as the Object to HashMap keys. Since String is immutable, its hashcode is cached at the time of creation and doesn’t need to be calculated again. This makes it a great candidate for the key in a Map, and it’s processing is fast than other HashMap key objects.

Heap Space

String immutability helps in saving a lot of Java heap space because different String variables can refer to the same String object in the pool. When Java code sees that two objects have the same value (a=”Generic Class”, and b=”Generic Class”), you need only one String object.

Wrong Assumption

If String is immutable, why is the following statement allowed?

String a = “Generic Class”;

a = “www.genericclass.com”;

One can say in the above statements that they are able to change the value of a String object from “Generic Class” to “www.genericclass.com." Then, what exactly does String immutability mean?

But wait, this assumption is wrong. In the above statements, you are not changing the value of the String object. Here, you are basically changing the reference. Previously, your variable a was pointing to an object that had the value “Generic Class."

But, in the second statement, a new object is created with value “www.genericclass.com” and your variable started to point to this new object.

String_Assingment.png

The older object still has the value “Generic Class.”

Well, that's all for now. In this post, we discussed some reasons why String is immutable. Hope you have enjoyed this post!

Reference:

https://dzone.com/articles/why-string-immutable-java

Strings Data Types

Published at DZone with permission of Nitin Ranjan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook