PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Why String is Immutable in Java

← All stacks

Theory

74/270

Why String is Immutable in Java

String is immutable so the String Pool can safely reuse literals — two "Java" literals can point to the same object. If String could change, one variable would surprise the other.

Immutability also helps HashMap keys (hashCode stays stable) and security (class names, passwords not silently edited).

When you need to change text many times, use StringBuilder. Don’t fight String with + in a loop.

Let's take this on the board with one tiny Main class — no extra files. Why String is Immutable in Java — output: Hi then Hi Java. concat without assign leaves a as Hi. a = a.concat(...) creates a new String. Start from main, go line by line, and stop at each print. That output is the proof for Why String is Immutable.

Exam tip

Why? Pool + HashMap keys + security. Then say StringBuilder when you need to edit.

Example

// Why String is immutable
public class Main {
  public static void main(String[] args) {
    String a = "Hi";
    a.concat(" Java");
    System.out.println(a); // still Hi
    a = a.concat(" Java");
    System.out.println(a); // Hi Java
  }
}

Why String is Immutable in Java — output: Hi then Hi Java. concat without assign leaves a as Hi. a = a.concat(...) creates a new String.

Short notes

  • DefString cannot change. Methods return a new String.
  • RulePool can reuse literals because content never changes.
  • RememberSafer HashMap keys + security.
  • UseMany edits → StringBuilder.

Questions

1

Why is String immutable?

2

What if you need to change text?

Previous← Java StringsNextString Comparison in Java →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.