Java 26-Day Course - Day 7: Strings

Day 7: Strings

String is the most commonly used class in Java. Strings are immutable — once created, their contents cannot be changed. Methods that modify strings always return a new String object.

Basic String Methods

Let’s explore the essential methods for working with strings.

public class StringMethods {
    public static void main(String[] args) {
        String text = "Hello, Java World!";

        // Length and index
        System.out.println("Length: " + text.length());          // 18
        System.out.println("Char at 2: " + text.charAt(2));     // l
        System.out.println("Index of Java: " + text.indexOf("Java")); // 7

        // Case conversion
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());

        // Substring
        System.out.println("Substring: " + text.substring(7, 11)); // Java
        System.out.println("From 7: " + text.substring(7));        // Java World!

        // Whitespace removal
        String padded = "  Hello  ";
        System.out.println("trim: [" + padded.trim() + "]");
        System.out.println("strip: [" + padded.strip() + "]"); // Java 11+

        // Contains check
        System.out.println("Contains Java? " + text.contains("Java")); // true
        System.out.println("Starts with Hello? " + text.startsWith("Hello")); // true
        System.out.println("Ends with !? " + text.endsWith("!"));     // true

        // Empty string check
        System.out.println("Is empty? " + "".isEmpty());  // true
        System.out.println("Is blank? " + "  ".isBlank()); // true (Java 11+)
    }
}

String Transformation and Splitting

Let’s learn how to split, join, and transform strings.

public class StringTransform {
    public static void main(String[] args) {
        // replace: string substitution
        String original = "Java is fun. Let's learn Java!";
        String replaced = original.replace("Java", "Python");
        System.out.println(replaced);

        // split: string splitting
        String csv = "John,25,Seoul,Developer";
        String[] parts = csv.split(",");
        for (String part : parts) {
            System.out.println(part);
        }

        // join: string concatenation
        String joined = String.join(" - ", "Java", "Python", "Go");
        System.out.println(joined); // Java - Python - Go

        // format: formatted string
        String name = "John";
        int age = 25;
        double height = 175.5;
        String formatted = String.format("Name: %s, Age: %d, Height: %.1fcm",
                                          name, age, height);
        System.out.println(formatted);

        // String -> number, number -> String
        int num = Integer.parseInt("123");
        double dbl = Double.parseDouble("3.14");
        String str = String.valueOf(456);
        System.out.println(num + dbl); // 126.14
    }
}

StringBuilder

When concatenating strings repeatedly, StringBuilder provides much better performance.

public class StringBuilderExample {
    public static void main(String[] args) {
        // Problem with String concatenation (creates a new object each time)
        String result = "";
        for (int i = 0; i < 5; i++) {
            result += i + " "; // Inefficient!
        }
        System.out.println(result);

        // StringBuilder: mutable string (efficient)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            sb.append(i).append(" ");
        }
        System.out.println(sb.toString());

        // Key StringBuilder methods
        StringBuilder builder = new StringBuilder("Hello");
        builder.append(" World");           // Append at the end
        builder.insert(5, ",");             // Insert at position
        builder.replace(0, 5, "Hi");        // Replace range
        builder.delete(2, 3);               // Delete range
        builder.reverse();                  // Reverse
        System.out.println(builder);

        // Chaining pattern
        String html = new StringBuilder()
            .append("<html>")
            .append("<body>")
            .append("<h1>Title</h1>")
            .append("</body>")
            .append("</html>")
            .toString();
        System.out.println(html);
    }
}

String Comparison and Searching

Important considerations when comparing strings, and basic regex usage.

public class StringComparison {
    public static void main(String[] args) {
        // equals vs ==
        String a = "hello";
        String b = new String("hello");
        System.out.println(a == b);             // false (reference comparison)
        System.out.println(a.equals(b));        // true (content comparison)
        System.out.println(a.equalsIgnoreCase("HELLO")); // true

        // compareTo: lexicographic comparison
        System.out.println("apple".compareTo("banana")); // negative (apple comes first)
        System.out.println("banana".compareTo("apple")); // positive (banana comes after)
        System.out.println("apple".compareTo("apple"));  // 0 (equal)

        // Basic regex
        String email = "user@example.com";
        boolean isValid = email.matches("[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+");
        System.out.println("Valid email: " + isValid); // true

        // replaceAll (regex)
        String text = "Phone: 010-1234-5678, Fax: 02-999-0000";
        String masked = text.replaceAll("\\d{3,4}-\\d{4}", "****-****");
        System.out.println(masked);

        // Text blocks (Java 15+)
        String json = """
                {
                    "name": "John",
                    "age": 25
                }
                """;
        System.out.println(json);
    }
}

Today’s Exercises

  1. Word Counter: Count the number of words separated by spaces in the string "Java is a powerful and popular programming language" and print each word with its number.

  2. String Reversal: Convert the string "Hello Java" to a char array without using StringBuilder and print the reversed result.

  3. Email Parser: Extract the username (developer), domain (company.co.kr), and top-level domain (kr) from the email address "developer@company.co.kr" and print each one.

Was this article helpful?