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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • Internal Developer Portals: Modern DevOps's Missing Piece
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • Java Virtual Threads and Scaling
  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 user avatar
Nitin Ranjan
·
Updated Oct. 30, 18 · Presentation
Likes (9)
Comment
Save
Tweet
Share
55.6K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!