Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn String Immutability in Java | Strings
Introduction to Java

String Immutability in Java

Swipe to show menu

You already know that Strings store text like customer names, product names, and messages. But one thing that makes Strings special in Java is that they are immutable.

Immutability means that once a String object is created, its content cannot be changed. Any operation that looks like it modifies a string actually creates a new String object behind the scenes.

Example

Main.java

Main.java

123456789101112131415
package com.example; public class Main { public static void main(String[] args) { int stock = 20; String drink = "Espresso"; stock = 15; drink = "Cappuccino"; System.out.println(stock); // 15 System.out.println(drink); // Cappuccino } }

Even though both variables were reassigned, they behave differently internally. With int, the variable directly stores the value — reassigning simply replaces it. But String is a reference type, meaning the variable stores an address pointing to a String object in memory. When drink = "Cappuccino" is assigned, Java doesn't modify "Espresso" — it creates a brand new String object and makes drink point to it instead. The original "Espresso" object remains unchanged.

How It Works Step by Step

String drink = "Espresso";

Java creates a String object "Espresso" and drink points to it.

drink = "Cappuccino";

Java creates a new String object "Cappuccino", drink now points to the new one. "Espresso" is untouched.

question mark

What does it mean that Strings are immutable in Java?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 4. Chapter 1
some-alt