Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Strings in Java

Types of Strings in Java

Strings in Java are of two types:

1️⃣ Mutable Strings – These strings can be changed after creation.

2️⃣ Immutable Strings – These strings cannot be changed after creation.

Mutable Strings in Java

Mutable strings are strings that can be changed after they are created. In Java, mutable strings are handled using StringBuffer and StringBuilder classes.

Different Ways to Create Mutable Strings

  1. Using StringBuffer:

    StringBuffer sb = new StringBuffer("java");
  2. Using StringBuilder:

    StringBuilder sb = new StringBuilder("java");

Key Differences Between String, StringBuffer, and StringBuilder

Feature

String (Immutable)

StringBuffer (Mutable)

StringBuilder (Mutable)

Thread-Safe

Yes

Yes

No

Performance

Slow (New object created every time modified)

Moderate (Synchronized)

Fast (Not synchronized)

Mutability

No

Yes

Yes

Immutable Strings in Java

Immutable strings are strings that cannot be changed or modified after they are created. In Java, immutable strings are created using the String class.

Different Ways to Create Immutable Strings

  1. Using a character array:

    char name[] = { 'j', 'a', 'v', 'a' };
    String s = new String(name);
  2. Using string literals:

    String s = "java";
  3. Using the new keyword:

    String s = new String("java");