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
123456789101112131415package 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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat