Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Why Java Strings are Immutable?
Next article icon

Why Java Strings are Immutable?

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, strings are immutable means their values cannot be changed once they are created. This feature enhances performance, security, and thread safety. In this article, we are going to learn why strings are immutable in Java and how this benefits Java applications.

What Does Immutable Mean?

When we say something is immutable, it means that once it is created, it cannot be changed. In Java, this concept applies to strings, which means that once a string object is created, its content cannot be changed. If we try to change a string, Java does not modify the original one, it creates a new string object instead.

How are Strings Immutable in Java?

Java strings are immutable to make sure memory is used efficiently. Strings in Java that are specified as immutable as the content is shared storage in a single pool to minimize creating a copy of the same value. String class and all wrapper classes in Java that include Boolean, Character, Byte, Short, Integer, Long, Float, and Double are immutable. A user is free to create immutable classes of their own.

When we use methods like concat() or replace(), they don’t alter the original string but create a new one with the new content. This helps avoid bugs that might arise from modifying shared data across different parts of the program.

Let's understand this with an example:

Java
public class Main {      public static void main(String[] args) {          String s1 = "knowledge";         String s2 = s1;            // s2 points to the same "knowledge"         s1 = s1.concat(" base");   // creates a new String "knowledge base"          System.out.println(s1);        } } 

Output
knowledge base 

Explanation: When we call s1.concat(" base"), it does not modify the original string "knowledge". It only creates a new string "knowledge base" and assigns it to s1. The original string remains unchanged.

Why Are Java Strings Immutable?

  • String Pool: Java stores string literals in a pool to save memory. Immutability ensures one reference does not change the value for others pointing to the same string.
  • Security: Strings are used for sensitive data like usernames and passwords. Immutability prevents attackers from altering the values.
  • Thread Safety: Since string values cannot be changed, they are automatically thread-safe, means multiple threads can safely use the same string.
  • Efficiency: The JVM reuses strings in the String Pool by improving memory usage and performance.

Example to Demonstrate String Immutability

The below program demonstrate the immutability of Java strings, where we try to modify a string using concat():

Java
// Java Program to demonstrate why // Java Strings are immutable import java.io.*;  class GFG {        public static void main(String[] args) {                String s1 = "java";                // creates a new String "java rules",          // but does not change s1         s1.concat(" rules");          // s1 still refers to "java"         System.out.println("s1 refers to " + s1);     } } 

Output
s1 refers to java 

Explanation: In the above example, even though we call concat() to append " rules", the original string s1 still refers to "java". The new string "java rules" is created, but it is not assigned to any variable, so it is lost.


Next Article
Why Java Strings are Immutable?

V

vaibhav shukla 5
Improve
Article Tags :
  • Strings
  • Java
  • DSA
  • Java-Strings
Practice Tags :
  • Java
  • Java-Strings
  • Strings

Similar Reads

    Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
    4 min read
    Immutable Set in Java
    As the name suggest these Set are immutable. If any attempt made to add, delete and update elements in the set we will have UnsupportedOperationException. An ImmutableSet does not allow null element either. If any attempt made to create an ImmutableSet with null element, we will have NullPointerExce
    3 min read
    Immutable List in Java
    ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An I
    5 min read
    How to Initialize and Compare Strings in Java?
    String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization wi
    5 min read
    String Class in Java
    A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences