Java Tutorial » Chapter 15 — Strings Class

Chapter 15 — Java Strings Class

Mastering text manipulation, immutability, and performance with the String class.

1. Introduction & Immutability

What is a Java String?

In Java, a string is an object that represents a sequence of characters. java.lang.String is a final class, which means you cannot inherit from it. The most important property of the String class is that it is immutable.

Immutability means that once a String object is created, its value cannot be changed. Any operation that appears to modify a string (like concatenation) actually creates a new String object in memory.

public class ImmutabilityDemo {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = s1.concat(" World"); // s1 is NOT changed. A new string is created.
        
        System.out.println(s1); // Outputs: Hello
        System.out.println(s2); // Outputs: Hello World
    }
}
2. Creating Strings

Ways to Create a String

There are two main ways to create a String object:

  • String Literal: Java optimizes string literals by storing them in a special memory area called the "String Pool". If you create another string with the same literal, it will point to the same object.
  • Using the new Keyword: This always creates a new object in the heap memory, even if the content is the same as a literal.
public class CreatingStrings {
    public static void main(String[] args) {
        // Using a String Literal
        String s1 = "Java";
        String s2 = "Java"; // Points to the same object as s1 in the String Pool

        // Using the 'new' keyword
        String s3 = new String("Java"); // A new object in the heap

        System.out.println(s1 == s2); // true (same reference)
        System.out.println(s1 == s3); // false (different references)
        System.out.println(s1.equals(s3)); // true (same content)
    }
}
3. StringBuffer & StringBuilder

Mutable String Alternatives

When you need to modify a string frequently (e.g., in a loop), using the immutable String class is inefficient because it creates many intermediate objects. For this, Java provides StringBuffer and StringBuilder.

  • StringBuilder: Introduced in Java 5. It is not synchronized, which makes it faster. It should be your default choice for string manipulation in a single-threaded environment.
  • StringBuffer: It is synchronized, meaning it is thread-safe. Use it only when multiple threads are accessing and modifying the same string buffer. It's slower than StringBuilder.
4. StringBuffer Methods

Common Mutable Operations

These methods are available for both StringBuffer and StringBuilder. The examples will use StringBuilder for performance.

Java – append() Method

The append() method is used to append text to the end of the current sequence.

public class AppendExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");
        sb.append("!");
        System.out.println(sb.toString()); // Outputs: Hello World!
    }
}

Java – reverse() Method

The reverse() method reverses the characters in the buffer.

public class ReverseExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("racecar");
        sb.reverse();
        System.out.println(sb.toString()); // Outputs: racecar
    }
}

Java – delete() Method

The delete(int start, int end) method removes characters from the buffer, from start (inclusive) to end (exclusive).

public class DeleteExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java is fun!");
        sb.delete(4, 7); // Deletes " is"
        System.out.println(sb.toString()); // Outputs: Java fun!
    }
}

Java – insert() Method

The insert(int offset, ...) method inserts a string or other data at the specified position.

public class InsertExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java is fun!");
        sb.insert(8, "very "); // Inserts "very " at index 8
        System.out.println(sb.toString()); // Outputs: Java is very fun!
    }
}

Java – replace() Method

The replace(int start, int end, String str) method replaces characters in a substring with another string.

public class ReplaceExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java is fun!");
        sb.replace(8, 11, "awesome"); // Replaces "fun" with "awesome"
        System.out.println(sb.toString()); // Outputs: Java is awesome!
    }
}
5. String Basics

Length, Concatenation, and Formatting

String Length

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

public class LengthExample {
    public static void main(String[] args) {
        String s = "Java Programming";
        System.out.println("Length is: " + s.length()); // Outputs: 17
    }
}

Concatenating Strings

The + operator is overloaded for string concatenation. The concat() method does the same thing.

public class ConcatExample {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = " World";
        String s3 = s1 + s2; // Using + operator
        String s4 = s1.concat(s2); // Using concat method
        System.out.println(s3); // Hello World
        System.out.println(s4); // Hello World
    }
}

Creating Format Strings

The String.format() method allows you to create formatted strings, similar to printf in C/C++.

public class FormatExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;
        String formatted = String.format("Name: %s, Age: %d", name, age);
        System.out.println(formatted); // Outputs: Name: Alice, Age: 30
    }
}
6. Character Access

Getting Characters from a String

Java – charAt() Method

Returns the character at the specified index. Indexing starts at 0.

public class CharAtExample {
    public static void main(String[] args) {
        String s = "Java";
        char ch = s.charAt(1); // Gets the character at index 1
        System.out.println(ch); // Outputs: a
    }
}

Java – getChars() Method

Copies characters from the string into a destination character array.

public class GetCharsExample {
    public static void main(String[] args) {
        String s = "Hello World";
        char[] dest = new char[5];
        // Copy characters from index 6 to 10 into 'dest'
        s.getChars(6, 11, dest, 0);
        System.out.println(dest); // Outputs: World
    }
}

Java – toCharArray() Method

Converts the entire string into a new character array.

public class ToCharArrayExample {
    public static void main(String[] args) {
        String s = "Java";
        char[] charArray = s.toCharArray();
        for (char c : charArray) {
            System.out.print(c + " "); // Outputs: J a v a 
        }
    }
}
7. Comparison Methods

Comparing Strings

Java – equals() & equalsIgnoreCase()

equals() checks for content equality (case-sensitive). equalsIgnoreCase() does the same but ignores case.

public class EqualsExample {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = "java";
        System.out.println(s1.equals(s2)); // false
        System.out.println(s1.equalsIgnoreCase(s2)); // true
    }
}

Java – compareTo() & compareToIgnoreCase()

Compares strings lexicographically (alphabetically). Returns a negative, zero, or positive integer.

public class CompareToExample {
    public static void main(String[] args) {
        String s1 = "Apple";
        String s2 = "Banana";
        System.out.println(s1.compareTo(s2)); // Negative value
        System.out.println(s2.compareTo(s1)); // Positive value
        System.out.println(s1.compareTo("Apple")); // 0
    }
}
8. Searching Methods

Finding Characters and Substrings

Java – indexOf() & lastIndexOf()

Finds the first or last occurrence of a character or substring. Returns -1 if not found.

public class IndexOfExample {
    public static void main(String[] args) {
        String s = "abracadabra";
        System.out.println(s.indexOf('a')); // 0
        System.out.println(s.lastIndexOf('a')); // 10
        System.out.println(s.indexOf("cad")); // 4
        System.out.println(s.indexOf('a', 5)); // 7 (searches from index 5)
    }
}

Java – startsWith() & endsWith()

Checks if the string starts or ends with a specific prefix or suffix.

public class StartEndExample {
    public static void main(String[] args) {
        String filename = "document.pdf";
        System.out.println(filename.startsWith("doc")); // true
        System.out.println(filename.endsWith(".pdf")); // true
        System.out.println(filename.endsWith(".txt")); // false
    }
}
9. Modification Methods

Creating Modified Versions of a String

Remember, these methods do not change the original string. They return a new one.

Java – substring() Method

Extracts a substring. substring(beginIndex) goes to the end. substring(beginIndex, endIndex) is exclusive of the end index.

public class SubstringExample {
    public static void main(String[] args) {
        String s = "Hello World";
        System.out.println(s.substring(6)); // "World"
        System.out.println(s.substring(0, 5)); // "Hello"
    }
}

Java – replace() & replaceAll()

replace() replaces all occurrences of a character or CharSequence. replaceAll() uses regular expressions for powerful replacements.

public class ReplaceExample {
    public static void main(String[] args) {
        String s = "Java is great. Java is fun.";
        System.out.println(s.replace('a', 'A')); // JAvA is greAt. JAvA is fun.
        System.out.println(s.replace("is", "was")); // Java was great. Java was fun.
        // Replace all non-alphabetic characters with a space
        System.out.println(s.replaceAll("[^a-zA-Z]", " ")); // Java is great Java is fun 
    }
}

Java – split() Method

Splits the string into an array of substrings based on a delimiter (which can be a regular expression).

public class SplitExample {
    public static void main(String[] args) {
        String data = "apple,banana,cherry";
        String[] fruits = data.split(",");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Java – trim() Method

Removes any leading and trailing whitespace from the string.

public class TrimExample {
    public static void main(String[] args) {
        String s = "   some text with spaces   ";
        System.out.println(s.trim()); // "some text with spaces"
    }
}

Java – toUpperCase() & toLowerCase()

Converts all characters in the string to uppercase or lowercase.

public class CaseExample {
    public static void main(String[] args) {
        String s = "Java Programming";
        System.out.println(s.toUpperCase()); // JAVA PROGRAMMING
        System.out.println(s.toLowerCase()); // java programming
    }
}
10. Conversion & Utility

Other Useful String Methods

Java – valueOf() Method

A static method that converts various data types (like int, double, boolean) into their string representation.

public class ValueOfExample {
    public static void main(String[] args) {
        int num = 100;
        double d = 99.99;
        boolean bool = true;
        
        System.out.println(String.valueOf(num)); // "100"
        System.out.println(String.valueOf(d));  // "99.99"
        System.out.println(String.valueOf(bool)); // "true"
    }
}
11. Practice & Challenge

Test Your Skills

  1. Write a program to check if a given string is a palindrome (ignoring case and non-alphanumeric characters).
  2. Write a program to reverse each word in a sentence while keeping the word order the same (e.g., "Hello World" -> "olleH dlroW").
  3. Write a program to count the number of occurrences of a specific word in a text.
  4. Write a program that takes a full name (e.g., "john doe") and capitalizes the first letter of each part (e.g., "John Doe").
  5. Write a program to find the longest word in a given string.

🏆 Challenge: Simple Text Processor

Create a program that takes a block of text and performs a series of transformations on it using the methods you've learned. The program should:

  • Count the total number of words.
  • Find and print the longest word.
  • Replace all occurrences of a specific word (provided by the user) with another word.
  • Print the final, modified text.

import java.util.Scanner;

public class TextProcessor {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("--- Simple Text Processor ---");
        System.out.print("Enter a block of text:\n");
        String text = scanner.nextLine();

        // 1. Count words
        String[] words = text.trim().split("\\s+");
        System.out.println("\nTotal words: " + words.length);

        // 2. Find longest word
        String longestWord = "";
        for (String word : words) {
            if (word.length() > longestWord.length()) {
                longestWord = word;
            }
        }
        System.out.println("Longest word: " + longestWord);

        // 3. Replace a word
        System.out.print("\nEnter word to replace: ");
        String toReplace = scanner.nextLine();
        System.out.print("Enter replacement word: ");
        String replacement = scanner.nextLine();
        
        String modifiedText = text.replace(toReplace, replacement);
        
        // 4. Print final text
        System.out.println("\n--- Modified Text ---");
        System.out.println(modifiedText);

        scanner.close();
    }
}