BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Immutable String in Java

Last Updated: June 9, 2024 by Chaitanya Singh | Filed Under: java

A String in Java is immutable, which means once you create a String object, its value cannot be changed. Any changes (such as concatenation) made to the string will create a new String object. This immutable nature of String in Java provides several advantages such as security, thread safety, and performance.

Features of Immutable Strings in Java

There are several advantages of immutable string in Java, some of them are:

  1. Security: Immutability ensures that sensitive data stored as strings such as passwords, user personal details etc. cannot be changed once created. This makes data stored as strings more secure.
  2. Thread Safety: Immutability makes string thread-safe, which means multiple strings can access string objects at the same time. This improves performance.
  3. Caching and Memory Management: Java uses a string pool to manage string literals. A string literal is a string that is created without using new keyword, for example: String str = “hello”; If a string is created with a value that already exist in the pool, then JVM returns the reference of existing string. This reduces memory usage.

Examples of Immutability

In this example, we have a string str, which contains the value “Hello”, when we concat a string to str, it creates a new string object modifiedStr with the value "Hello, World!".

public class ImmutableStringExample {
public static void main(String[] args) {
String str = "Hello";
String modifiedStr = str.concat(", World!");

System.out.println("Original String: " + str); // Output: Hello
System.out.println("Modified String: " + modifiedStr); // Output: Hello, World!
}
}

How Immutable Strings Work

  1. String Pool: Java maintains a string pool, when you create a new string, JVM checks in the string pool. If the identical string is found in the pool, JVM returns reference to it.
  2. String Methods: Java String Methods such as substring(), concat(), replace(), etc do not change the original string. Instead, they create and return a new string.

Example of String Pool

In this example, we create two strings s1 and s2 using string literals (without using new keyword). String s3 is created using new keyword. Hence s1 and s2 refers to the same string in the pool, however s3 refers to different object because it is created using new keyword.

public class StringPoolExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");

// true, both refer to the same string in the pool
System.out.println(s1 == s2);
// false, s3 refers to a new string object
System.out.println(s1 == s3);
}
}

Example of String Methods

In this example, when we used toUpperCase() method on string str, it didn’t change the value of str, rather returned a new string object with modified value.

public class StringMethodsExample {
public static void main(String[] args) {
String str = "java";
String str2 = str.toUpperCase();

System.out.println(str); // Output: java
System.out.println(str2); // Output: JAVA
}
}

Top Related Articles:

  1. Toggle String in Java
  2. C++ vs Java – Difference between C++ and Java
  3. Constructor Overloading in Java with examples
  4. Introduction to Java programming
  5. Java 9 – Factory method to create Immutable List

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap