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

Why String Immutable or Final in Java

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: java

The immutable and final nature of String class is intentional. This is by design to offer several features and advantages. In this guide, we will discuss these advantages with examples.

Reasons for String Immutability

  1. Security:
    • Sensitive Data: Immutability feature of String offers security as data cannot be changed, this is exactly what we want for sensitive information such as password, bank details etc. This also ensures that data is safe from unintentional change due to some vulnerability.
  2. Thread Safety:
    • Concurrent Access: Since strings are immutable, they are inherently thread-safe, this means multiple threads can access same string at the same time.
    • Consistency: Since, you cannot change an immutable string. This means all threads accessing the string sees same consistent value and there is no risk of one thread changing the string while another thread is using it.
  3. Caching and Performance:
    • String Pooling: Java uses a string pool to manage string literals. A string literal is a string created without using new keyword, for example: String str = “hello”; If a string is created with a value that is already present in the pool, then JVM returns the reference of existing string.
    • HashCode Caching: Hashing provides faster operations, Immutable strings can cache their hash codes when they are created. This remains consistent as the string doesn’t change.
  4. Memory Efficiency:
    • Shared Substrings: A string is nothing but a character array, immutable string can share their array with substrings.
  5. By design:
    • Final Class: To make string class consistent, it is declared final. This ensures that subclasses do not alter its immutability.
    • Design Principle: The string class is designed in such a way that the operations and output are straightforward and consistent.

Example of Benefits

In the following example, String str2 remains "Hello" even after str1 is modified because strings are immutable. This demonstrates that immutability preserves the original state.

public class StringImmutabilityExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1;

// Concatenation resulted a new string, str1 is now
// points to this new concatenated string
str1 = str1 + " World";

// str1 now refers to a new string, but str2 remains unchanged
// because the old string "Hello" remains unchanged in memory
System.out.println("str1: " + str1); // Output: str1: Hello World
System.out.println("str2: " + str2); // Output: str2: Hello
}
}

Top Related Articles:

  1. OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
  2. What is the difference between a process and a thread in Java?
  3. Basics: All about Java threads
  4. Polymorphism in Java with example
  5. Constructor Overloading in Java with examples

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