Topic 76 of 119 7. Arrays and Strings in Java Interactive Tutorial

Java String Class: Immutability, String Pool, and Core Methods

10 mins read Last updated: 22 Aug 2026 28,148 views

Direct Answer & Core Concept

The String class is one of the most frequently used classes in Java. Strings are used to store names, messages, URLs, passwords, file paths, user input, and almost every other type of text.

Java provides many built-in methods for creating, comparing, searching, modifying, and processing strings. Understanding String immutability, the String Pool, and the difference between == and equals() is especially important for Java programming and interviews.

Detailed Explanation & Mechanics

What Is a String in Java?

A String represents a sequence of characters. Java provides the String class in the java.lang package, so you can use it without explicitly importing it.

Here, name refers to a String object containing the characters Admin.

Strings can contain letters, numbers, spaces, symbols, and special characters.

Main.java
Run Online
String message = "Hello Java!";

Why Is String Important in Java?

Strings are used in almost every Java application. They are commonly used for displaying messages, processing user input, reading files, working with databases, handling URLs, and communicating with APIs.

For example:

Main.java
Run Online
String username = "admin";
String email = "user@example.com";
String url = "https://example.com";

Because strings are so common, Java provides a large collection of built-in String methods.


String Is a Class in Java

Unlike primitive types such as int, double, and char, String is a class.

The String class provides methods such as:

Main.java
Run Online
text.length();
text.toUpperCase();
text.toLowerCase();
text.contains("av");

Since String belongs to java.lang, no import statement is required.


Creating a String

There are two common ways to create a String.

Using a String Literal

Main.java
Run Online
String language = "Java";

This is the most common approach.

Using the new Keyword

Main.java
Run Online
String language = new String("Java");

Both create a String containing "Java", but they interact differently with the String Pool.

For normal String values, literals are generally preferred.


String Literals

A String literal is text written inside double quotation marks.

Main.java
Run Online
String name = "John";
String city = "Kolkata";
String message = "Welcome to Java";

Java handles String literals specially through the String Pool.

This allows identical String literals to share the same pooled object.


What Is the String Pool?

The String Pool, also called the String Intern Pool, is a special area associated with the JVM's management of String objects.

When Java encounters identical String literals, it can reuse the same pooled String object instead of creating another identical object.

For example:

Main.java
Run Online
String a = "Java";
String b = "Java";

Both variables can refer to the same pooled String object.

Conceptually:

Architecture Diagram
a ─────┐
       ▼
    "Java"
       ▲
       │
b ─────┘

This reduces unnecessary duplicate String objects.


String Pool Example

Consider:

Main.java
Run Online
String a = "Java";
String b = "Java";
System.out.println(a == b);

Output:

Both variables refer to the same pooled String object in this case.

However, this does not mean == should generally be used to compare String contents.

For content comparison, use equals().


Creating Strings with new

Now consider:

Main.java
Run Online
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);

Output:

Each new String() expression creates a distinct String object.

The strings contain the same characters, but the object references are different.


String Pool vs new String()

Compare these examples:

Main.java
Run Online
String a = "Java";
String b = "Java";

The literals can share the pooled object.

But:

Main.java
Run Online
String x = new String("Java");
String y = new String("Java");

creates separate String objects.

The important lesson is that String content equality and object reference equality are different concepts.


What Is String Immutability?

Strings in Java are immutable. This means that once a String object has been created, its character contents cannot be changed.

For example:

Main.java
Run Online
String text = "Java";
text.concat(" Programming");
System.out.println(text);

Output:

The concat() operation creates another String rather than changing the original String.


Creating a New String After Modification

To keep the result, assign the returned String to a variable.

Main.java
Run Online
String text = "Java";
text = text.concat(" Programming");
System.out.println(text);

Output:

The original "Java" String object was not modified. A new String was created and the variable was updated to refer to it.


Why Are Strings Immutable?

String immutability provides several useful properties. Strings can be safely shared, reused through the String Pool, and used as keys in hash-based collections.

It also makes String objects predictable because their contents cannot unexpectedly change after creation.

This is one reason String is designed differently from mutable classes such as StringBuilder.


String Immutability Example

Consider:

Main.java
Run Online
String name = "Java";
name.toUpperCase();
System.out.println(name);

Output:

toUpperCase() does not modify the original String.

Correct usage:

Main.java
Run Online
name = name.toUpperCase();

Now the variable refers to the resulting String.


== vs equals() for Strings

This is one of the most important Java String concepts.

The == operator compares whether two references refer to the same object.

The equals() method compares the actual String contents.

Main.java
Run Online
String a = "Java";
String b = new String("Java");
System.out.println(a == b);
System.out.println(a.equals(b));

Output:

The contents are equal, but the objects are different.


Why You Should Use equals()

When comparing String values, use:

rather than:

For example:

Main.java
Run Online
String username = "admin";
if (username.equals("admin")) {
    System.out.println("Login allowed");
}

This checks the actual content of the strings.


Using equalsIgnoreCase()

Sometimes you want to compare strings without considering uppercase and lowercase differences.

Use:

Main.java
Run Online
String a = "Java";
String b = "java";
System.out.println(a.equalsIgnoreCase(b));

Output:

This is useful for case-insensitive comparisons.


The length() Method

The length() method returns the number of characters in a String.

Main.java
Run Online
String text = "Java";
System.out.println(text.length());

Output:

Unlike arrays, Strings use length() with parentheses.

Remember:

but:


The charAt() Method

The charAt() method returns the character at a specified index.

Indexes start at 0.

Main.java
Run Online
String text = "Java";
System.out.println(text.charAt(0));
System.out.println(text.charAt(2));

Output:

The valid index range is from 0 to length() - 1.


The substring() Method

substring() extracts part of a String.

Main.java
Run Online
String text = "Programming";
String result = text.substring(0, 7);
System.out.println(result);

Output:

The starting index is included, while the ending index is excluded.


substring() with One Argument

You can provide only the starting index.

Main.java
Run Online
String text = "JavaProgramming";
String result = text.substring(4);
System.out.println(result);

Output:

The method returns everything from index 4 to the end of the String.


The contains() Method

The contains() method checks whether a String contains a specified sequence.

Main.java
Run Online
String text = "Learn Java Programming";
System.out.println(text.contains("Java"));

Output:

The result is a boolean value: true if the sequence exists and false otherwise.


The startsWith() Method

Use startsWith() to check whether a String begins with specific text.

Main.java
Run Online
String url = "https://example.com";
System.out.println(url.startsWith("https"));

Output:

This can be useful when checking URLs, file names, commands, or prefixes.


The endsWith() Method

The endsWith() method checks whether a String ends with specific text.

Main.java
Run Online
String file = "document.pdf";
System.out.println(file.endsWith(".pdf"));

Output:

It is commonly used for checking file extensions.


The indexOf() Method

indexOf() returns the position of the first occurrence of a character or String.

Main.java
Run Online
String text = "Java Programming";
System.out.println(text.indexOf("Programming"));

The method returns the starting index of the matching text.

If the requested value cannot be found, indexOf() returns -1.


The lastIndexOf() Method

lastIndexOf() searches from the end of the String and returns the position of the last occurrence.

Main.java
Run Online
String text = "Java Java Java";
System.out.println(text.lastIndexOf("Java"));

This is useful when you need the final occurrence of a character or substring.


The toUpperCase() Method

This method returns a new String with letters converted to uppercase.

Main.java
Run Online
String text = "hello java";
String result = text.toUpperCase();
System.out.println(result);

Output:

The original String remains unchanged because Strings are immutable.


The toLowerCase() Method

toLowerCase() returns a new String containing lowercase letters.

Main.java
Run Online
String text = "HELLO JAVA";
String result = text.toLowerCase();
System.out.println(result);

Output:

Again, the original String is not modified.


The trim() Method

trim() removes leading and trailing whitespace from a String.

Main.java
Run Online
String text = "   Java   ";
System.out.println(text.trim());

Output:

It does not remove whitespace between words.

For example:

remains unchanged internally between the two words.


The strip() Method

Modern Java also provides strip() for removing leading and trailing Unicode whitespace.

Main.java
Run Online
String text = "   Java   ";
String result = text.strip();
System.out.println(result);

strip() is generally more Unicode-aware than the older trim() method.


The replace() Method

replace() replaces characters or character sequences.

Main.java
Run Online
String text = "Java is easy";
String result = text.replace("easy", "powerful");
System.out.println(result);

Output:

The original String remains unchanged.


The replaceAll() Method

replaceAll() works with regular expressions.

Main.java
Run Online
String text = "Java123";
String result = text.replaceAll("[0-9]", "");
System.out.println(result);

Output:

Use replaceAll() when you need pattern-based replacement.

For simple literal replacement, replace() is usually easier.


The split() Method

split() divides a String into an array of Strings.

Main.java
Run Online
String text = "Java,Python,PHP";
String[] languages = text.split(",");
for (String language : languages) {
    System.out.println(language);
}

Output:

This is particularly useful when processing comma-separated or delimiter-separated text.


The concat() Method

concat() joins one String to another.

Main.java
Run Online
String first = "Hello";
String result = first.concat(" Java");
System.out.println(result);

Output:

Because Strings are immutable, concat() returns a new String.


String Concatenation with +

The + operator can also combine Strings.

Main.java
Run Online
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName);

Output:

For simple concatenation, + is convenient and widely used.


String Concatenation with Numbers

Java can combine Strings and primitive values using +.

Main.java
Run Online
int age = 35;
String message = "Age: " + age;
System.out.println(message);

Output:

Java converts the numeric value into its String representation as part of the concatenation operation.


The isEmpty() Method

isEmpty() returns true when the String has zero characters.

Main.java
Run Online
String text = "";
System.out.println(text.isEmpty());

Output:

A String containing spaces is not empty:

Main.java
Run Online
String text = "   ";
System.out.println(text.isEmpty());

This returns false.


The isBlank() Method

isBlank() checks whether a String is empty or contains only whitespace.

Main.java
Run Online
String text = "   ";
System.out.println(text.isBlank());

Output:

This is useful when validating user input where whitespace-only input should be treated as missing.


Comparing Strings with compareTo()

compareTo() compares two strings lexicographically.

Main.java
Run Online
String a = "Apple";
String b = "Banana";
System.out.println(a.compareTo(b));

A negative result means the first String comes before the second according to the comparison.

A result of 0 means the strings are equal in the comparison.


Using compareToIgnoreCase()

You can perform a case-insensitive comparison using:

Main.java
Run Online
String a = "Java";
String b = "java";
System.out.println(a.compareToIgnoreCase(b));

Output:

This is useful when sorting or comparing text without considering letter case.


Converting Other Values to Strings

The String.valueOf() method can convert many values into String representations.

Main.java
Run Online
int number = 100;
String text = String.valueOf(number);
System.out.println(text);

Output:

This is useful when you need to convert primitive values into Strings.


Converting a String to an Integer

The reverse operation can be performed using wrapper classes.

Main.java
Run Online
String text = "100";
int number = Integer.parseInt(text);
System.out.println(number + 50);

Output:

The String must contain a valid integer representation or a NumberFormatException can occur.


Converting a String to a Double

You can also convert decimal text into a double.

Main.java
Run Online
String text = "25.50";
double price = Double.parseDouble(text);
System.out.println(price);

Output:

This is commonly used when processing numeric values received as text.


Getting the First Character

You can use charAt(0) to get the first character.

Main.java
Run Online
String name = "Java";
char first = name.charAt(0);
System.out.println(first);

Output:

Always make sure the String is not empty before accessing index 0.


Getting the Last Character

Use length() - 1 to find the last valid index.

Main.java
Run Online
String name = "Java";
char last = name.charAt(name.length() - 1);
System.out.println(last);

Output:

This is a common pattern when processing strings character by character.


Traversing a String

You can use a loop to visit every character.

Main.java
Run Online
String text = "Java";
for (int i = 0;
i < text.length();
i++) {
    System.out.println(text.charAt(i));
}

Output:

This technique is useful for counting characters, checking patterns, and processing individual characters.


Counting a Character

You can count how many times a particular character occurs.

Main.java
Run Online
String text = "banana";
int count = 0;
for (int i = 0;
i < text.length();
i++) {
    if (text.charAt(i) == 'a') {
        count++;
    }
}System.out.println("Count = " + count);

Output:

This is a useful beginner exercise for String processing.


Checking for a Palindrome

A palindrome reads the same from both directions.

For example:

A simple approach is to compare characters from opposite ends.

Main.java
Run Online
String text = "madam";
boolean palindrome = true;
for (int i = 0;
i < text.length() / 2;
i++) {
    if (text.charAt(i) != text.charAt(text.length() - 1 - i)) {
        palindrome = false;
        break;
    }
}System.out.println(palindrome);

Output:

This is a common Java String programming exercise.


String and char[]

A String can be converted into a character array using toCharArray().

Main.java
Run Online
String text = "Java";
char[] letters = text.toCharArray();
for (char letter : letters) {
    System.out.println(letter);
}

Output:

This can be useful when you need to work directly with individual characters.


Creating a String from char[]

You can also create a String from a character array.

Main.java
Run Online
char[] letters = {
    'J', 'a', 'v', 'a'
};
String text = new String(letters);
System.out.println(text);

Output:

This provides a simple way to move between String and character-array representations.


String Comparison Example

Consider:

Main.java
Run Online
String a = "Java";
String b = "Java";
String c = new String("Java");

Now:

Main.java
Run Online
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));

Output:

This demonstrates the difference between pooled String literals and separately created String objects.


Why String Pool Improves Memory Usage

Suppose a program creates the same String literal many times:

Main.java
Run Online
String a = "Java";
String b = "Java";
String c = "Java";

The JVM can reuse the same pooled String object for these identical literals.

Conceptually:

Architecture Diagram
a ──┐
b ──┼──> "Java"
c ──┘

Instead of requiring a separate identical object for every literal reference, the pool allows reuse.


The intern() Method

The intern() method returns the canonical representation of a String from the String Pool.

Example:

Main.java
Run Online
String a = new String("Java");
String b = a.intern();
String c = "Java";
System.out.println(b == c);

Output:

intern() is an advanced feature and should not be used automatically for every String. It is useful when you have a specific reason to work with pooled canonical String instances.


String Security and Immutability

String immutability can be useful when text values need to remain unchanged after creation.

For example, String values are commonly used in configuration, identifiers, file paths, and other application data.

However, immutable Strings should not automatically be considered secure storage for highly sensitive information such as passwords. Specialized handling may be appropriate for sensitive data.


String vs Character Array

A String and a char[] are different types.

Main.java
Run Online
String text = "Java";
char[] letters = {
    'J', 'a', 'v', 'a'
};

Strings are immutable and provide many convenient methods. Character arrays are mutable, so individual characters can be changed.

Choose the representation based on the requirements of the program.


String vs StringBuilder

String is immutable, while StringBuilder is mutable.

For example:

Repeated concatenation can create multiple intermediate String objects.

For many modifications, StringBuilder is often more appropriate:

Main.java
Run Online
StringBuilder builder = new StringBuilder();
builder.append("Java");
builder.append(" Programming");
System.out.println(builder);

Use String for normal text values and consider StringBuilder when building a String through many modifications.


String vs StringBuffer

StringBuffer is another mutable character sequence.

The main distinction commonly discussed is that StringBuffer provides synchronized methods, while StringBuilder is generally preferred for single-threaded String construction because it does not add that synchronization overhead.

Main.java
Run Online
StringBuffer buffer = new StringBuffer("Java");
buffer.append(" Programming");
System.out.println(buffer);

For ordinary String building in modern Java applications, StringBuilder is often the simpler choice when synchronization is not required.


Common String Methods

MethodPurpose
length()Returns String length
charAt()Gets a character
substring()Extracts part of a String
equals()Compares String contents
equalsIgnoreCase()Case-insensitive comparison
contains()Checks for a sequence
startsWith()Checks the beginning
endsWith()Checks the ending
indexOf()Finds first occurrence
lastIndexOf()Finds last occurrence
toUpperCase()Converts to uppercase
toLowerCase()Converts to lowercase
trim()Removes leading/trailing legacy whitespace
strip()Removes leading/trailing Unicode whitespace
replace()Replaces literal characters/sequences
replaceAll()Replaces using regex
split()Splits into an array
concat()Joins Strings
isEmpty()Checks zero length
isBlank()Checks empty/whitespace-only text
toCharArray()Converts to char[]
valueOf()Converts values to String

Common Mistakes with Java Strings

Mistake 1: Using == for Content Comparison

Avoid:

when your intention is to compare String contents.

Use:


Mistake 2: Forgetting String Immutability

This does not change the original String:

Main.java
Run Online
String text = "java";
text.toUpperCase();

Use:

Main.java
Run Online
text = text.toUpperCase();

if you want to keep the returned result.


Mistake 3: Calling charAt() on an Empty String

This causes an exception:

Main.java
Run Online
String text = "";
text.charAt(0);

Check the String before accessing a character.


Mistake 4: Invalid substring() Index

This can cause a StringIndexOutOfBoundsException:

Main.java
Run Online
String text = "Java";
text.substring(10);

Make sure the requested indexes are within the valid range.


Mistake 5: Confusing length and length()

For arrays:

For Strings:

This is a common beginner mistake.


Best Practices for Java Strings

Use String literals for normal String values instead of unnecessarily creating objects with new String().

Use equals() for content comparison and remember that String operations usually return new Strings because Strings are immutable.

For many repeated modifications, consider StringBuilder. For input validation, methods such as isBlank() can make the intent clearer.

Keep String-processing methods small and focused when building larger applications.


Complete Java String Example

The following example demonstrates several important String concepts together.

Main.java
Run Online
public class StringExample {
    public static void main(String[] args) {
        String text = "Java Programming";
        System.out.println("Text: " + text);
        System.out.println("Length: " + text.length());
        System.out.println("First character: " + text.charAt(0));
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());
        System.out.println("Contains Java: " + text.contains("Java"));
        System.out.println("Starts with Java: " + text.startsWith("Java"));
        System.out.println("Ends with ing: " + text.endsWith("ing"));
        System.out.println("Index of Programming: " + text.indexOf("Programming"));
        System.out.println("Substring: " + text.substring(5));
        String another = "Java Programming";
        System.out.println("Equals: " + text.equals(another));
        System.out.println("Same reference: " +(text == another));
    }
}

Possible output:

Main.java
Run Online
Text: Java ProgrammingLength: 16First character: JUppercase: JAVA PROGRAMMINGLowercase: java programmingContains Java: trueStarts with Java: trueEnds with ing: trueIndex of Programming: 5Substring: ProgrammingEquals: trueSame reference: true

The final == result is true here because both values are identical String literals and can refer to the same pooled object. You should still use equals() when your goal is content comparison.


Important Rules to Remember

  1. String is a class in Java.

  2. Strings are immutable.

  3. String literals are managed through the String Pool.

  4. == compares object references.

  5. equals() compares String contents.

  6. length() returns the number of characters.

  7. String indexes start at 0.

  8. String operations generally return new String objects.

  9. StringBuilder is useful for repeated String modification.

  10. isEmpty() checks zero characters.

  11. isBlank() also considers whitespace-only Strings.

  12. substring() uses a start index and optional end index.

  13. charAt() returns a character at a specific index.

  14. split() returns a String array.

  15. toCharArray() converts a String into a character array.


Frequently Asked Questions

Is String a primitive type in Java?

No. String is a class. It is a reference type provided by Java's standard library.

Why is String immutable in Java?

String immutability allows String objects to be safely shared and reused. It also works well with the String Pool and hash-based collections.

What is the String Pool?

The String Pool is an area managed by the JVM for canonical String literals. Identical String literals can share the same pooled object.

What is the difference between == and equals()?

== checks whether two references point to the same object. equals() checks whether two String objects contain equal text.

Why does a == b sometimes return true for Strings?

Identical String literals can refer to the same pooled object, so == may return true. This is why == should not be used as the general way to compare String contents.

Does toUpperCase() modify a String?

No. Strings are immutable. toUpperCase() returns a new String containing the uppercase result.

What is the difference between isEmpty() and isBlank()?

isEmpty() returns true only when the String has zero characters. isBlank() also returns true when the String contains only whitespace.

What is the difference between String and StringBuilder?

String is immutable. StringBuilder is mutable and is useful when a String needs to be built or changed repeatedly.

What does substring() do?

It returns a portion of a String based on the specified indexes.

How do I convert a String into a character array?

Use:

Main.java
Run Online
char[] letters = text.toCharArray();

How do I convert an integer to a String?

You can use:

Main.java
Run Online
String text = String.valueOf(100);

How do I convert a String into an integer?

Use:

Main.java
Run Online
int number = Integer.parseInt("100");

Quick Revision

The Java String class is used to represent text. Strings are immutable, meaning their contents cannot be changed after the String object is created.

The String Pool allows identical String literals to be reused:

Main.java
Run Online
String a = "Java";
String b = "Java";

For content comparison, use:

rather than:

Common String methods include:

Main.java
Run Online
length()charAt()substring()contains()equals()equalsIgnoreCase()indexOf()replace()split()toUpperCase()toLowerCase()trim()strip()isEmpty()isBlank()

The most important concept to remember is:

Main.java
Run Online
String↓Immutable↓Operations return new Strings↓String Pool can reuse literals↓equals() → content comparison== → reference comparison

Once these concepts are clear, Java String processing becomes much easier to understand.


Graphic and Image Design Ideas

Graphic 1: String Object Concept

Create a clean visual:

Architecture Diagram
String name = "Java";

name
 │
 ▼
┌───────────────┐
│ J │ a │ v │ a │
└───────────────┘

Label it "String object containing a sequence of characters".

Graphic 2: String Immutability

Show:

Architecture Diagram
String text = "Java";

text.toUpperCase();

"Java"  ───────→  "JAVA"
 original          new String

Highlight that the original "Java" object is not modified.

Graphic 3: String Pool

Show:

Architecture Diagram
String a = "Java";
String b = "Java";

a ─────┐
       ▼
     "Java"
       ▲
       │
b ─────┘

Add the label "Same pooled String object".

Graphic 4: == vs equals()

Create a side-by-side comparison:

Architecture Diagram
==

Checks references
Object A ──?── Object B


equals()

Checks contents
"Java" ──?── "Java"

This is one of the most useful graphics for beginner Java learners.

Graphic 5: Core String Methods

Create a visual showing:

Architecture Diagram
"Java Programming"
       │
       ├── length()
       ├── charAt()
       ├── substring()
       ├── contains()
       ├── indexOf()
       ├── replace()
       └── split()

Graphic 6: String vs StringBuilder

Use a comparison:

Main.java
Run Online
StringImmutable"Java" → "Java Programming"StringBuilderMutableappend() → append() → append()

Label when each is appropriate.

Graphic 7: String Processing Flow

Show:

Main.java
Run Online
Input String↓Validation↓Search / Compare↓Transform↓Final String

This gives beginners a simple mental model for practical String processing.

Runnable Code Example: Java String Class

Java 17+
Main.java
Run Online
public class StringImmutabilityDemo {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = "Java";
        // Reuses pool instance
        String s3 = new String("Java");
        // Distinct heap object
        System.out.println("s1 == s2: " +(s1 == s2));
        // true (same pool reference)
        System.out.println("s1 == s3: " +(s1 == s3));
        // false (different objects)
        System.out.println("s1.equals(s3): " + s1.equals(s3));
        // true (same content)
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

Why is String immutable in Java?

For security, thread-safety, memory optimization via the String Pool, and caching the hashCode for fast hash-map lookups.
Q2

What does the String.intern() method do?

It adds the string to the String Constant Pool if not already present and returns the canonical pool reference.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Always use .equals() for string comparison and avoid creating strings with new String() literals.