String Methods in Java

String Methods in Java

A comprehensive reference of all String methods with examples and explanations.

1. String Creation Methods

String()

Creates a new String object.

// Different ways to create strings
String str1 = "Hello";                    // String literal
String str2 = new String("World");        // Using constructor
char[] chars = {'J', 'a', 'v', 'a'};
String str3 = new String(chars);          // From char array
byte[] bytes = {74, 97, 118, 97};
String str4 = new String(bytes);          // From byte array
String str5 = new String(chars, 1, 2);    // From portion of char array

2. Length and Empty Checks

length()

Returns the length of the string.

String str = "Hello";
int len = str.length();  // 5

isEmpty()

Checks if the string is empty (length is 0).

String str1 = "";
String str2 = "Hello";
boolean empty1 = str1.isEmpty();  // true
boolean empty2 = str2.isEmpty();  // false

isBlank() Java 11+

Checks if the string is empty or contains only whitespace.

String str1 = "   ";
String str2 = "Hello";
boolean blank1 = str1.isBlank();  // true
boolean blank2 = str2.isBlank();  // false

3. Case Conversion

toLowerCase()

Converts all characters to lowercase.

String str = "Hello World";
String lower = str.toLowerCase();  // "hello world"

toUpperCase()

Converts all characters to uppercase.

String str = "Hello World";
String upper = str.toUpperCase();  // "HELLO WORLD"

4. Trimming and Whitespace

trim()

Removes leading and trailing whitespace.

String str = "  Hello World  ";
String trimmed = str.trim();  // "Hello World"

strip() Java 11+

Removes leading and trailing whitespace (Unicode-aware).

String str = "  Hello World  \u2005";
String stripped = str.strip();  // "Hello World"

stripLeading() Java 11+

Removes leading whitespace.

String str = "  Hello World  ";
String leading = str.stripLeading();  // "Hello World  "

stripTrailing() Java 11+

Removes trailing whitespace.

String str = "  Hello World  ";
String trailing = str.stripTrailing();  // "  Hello World"

5. String Comparison

equals(Object obj)

Compares the string with the specified object.

String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
boolean eq1 = str1.equals(str2);  // true
boolean eq2 = str1.equals(str3);  // false

equalsIgnoreCase(String str)

Compares strings ignoring case.

String str1 = "Hello";
String str2 = "HELLO";
boolean eq = str1.equalsIgnoreCase(str2);  // true

compareTo(String anotherString)

Compares strings lexicographically.

String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);  // negative (a < b)

compareToIgnoreCase(String str)

Compares strings lexicographically, ignoring case.

String str1 = "Apple";
String str2 = "banana";
int result = str1.compareToIgnoreCase(str2);  // negative (a < b)

contentEquals(CharSequence cs)

Compares string with any CharSequence.

String str = "Hello";
StringBuilder sb = new StringBuilder("Hello");
boolean equal = str.contentEquals(sb);  // true

Note on String Comparison

Always use equals() for string content comparison, not == (which checks for reference equality).

String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2);           // false (different objects)
System.out.println(s1.equals(s2));      // true (same content)

Performance Tip

For case-insensitive comparisons, equalsIgnoreCase() is more efficient than converting to lowercase/uppercase and then comparing.

6. Searching in Strings

indexOf()

Returns the index of the first occurrence of the specified character or substring.

String str = "Hello World";
int index1 = str.indexOf('o');        // 4
int index2 = str.indexOf("World");    // 6
int index3 = str.indexOf('o', 5);     // 7 (starts from index 5)
int index4 = str.indexOf("Java");     // -1 (not found)

lastIndexOf()

Returns the index of the last occurrence of the specified character or substring.

String str = "Hello World";
int last1 = str.lastIndexOf('o');      // 7
int last2 = str.lastIndexOf("or");     // 7
int last3 = str.lastIndexOf('o', 5);   // 4 (searches backward from index 5)
int last4 = str.lastIndexOf("Java");   // -1 (not found)

contains(CharSequence s)

Checks if the string contains the specified character sequence.

String str = "Hello World";
boolean hasHello = str.contains("Hello");   // true
boolean hasJava = str.contains("Java");     // false

startsWith(String prefix)

Checks if the string starts with the specified prefix.

String str = "Hello World";
boolean starts1 = str.startsWith("Hello");   // true
boolean starts2 = str.startsWith("World");   // false
boolean starts3 = str.startsWith("World", 6); // true (starts checking from index 6)

endsWith(String suffix)

Checks if the string ends with the specified suffix.

String str = "Hello World";
boolean ends1 = str.endsWith("World");   // true
boolean ends2 = str.endsWith("Hello");   // false

Performance Tip

For repeated searches in the same string, consider using Pattern and Matcher for better performance.

7. Substring and Character Extraction

charAt(int index)

Returns the character at the specified index.

String str = "Hello";
char ch = str.charAt(1);  // 'e'

substring()

Returns a substring of the string.

String str = "Hello World";
String sub1 = str.substring(6);      // "World"
String sub2 = str.substring(0, 5);   // "Hello" (end index is exclusive)

// Common use case: Extract domain from email
String email = "user@example.com";
String domain = email.substring(email.indexOf('@') + 1);  // "example.com"

codePointAt(int index)

Returns the Unicode code point at the specified index.

String str = "A";
int code = str.codePointAt(0);  // 65 (Unicode for 'A')

codePointBefore(int index)

Returns the Unicode code point before the specified index.

String str = "AB";
int code = str.codePointBefore(1);  // 65 (Unicode for 'A')

codePointCount(int beginIndex, int endIndex)

Returns the number of Unicode code points in the specified range.

String str = "Hello";
int count = str.codePointCount(0, str.length());  // 5

Important Note on substring()

In Java 7 and later, substring() creates a new character array instead of sharing the original one (as in Java 6 and earlier). This prevents memory leaks but may use more memory.

8. String Replacement

replace()

Replaces all occurrences of a character or character sequence.

String str = "Hello World";
String replaced1 = str.replace('l', 'L');      // "HeLLo WorLd"
String replaced2 = str.replace("World", "Java");  // "Hello Java"

// Replace all whitespace with underscore
String text = "Hello   World   ";
String clean = text.replace(" ", "_");  // "Hello___World___"

replaceAll()

Replaces all substrings that match the given regular expression.

String str = "Hello123World456";
String lettersOnly = str.replaceAll("\\d+", "");  // "HelloWorld"
String formatted = "Name: John, Age: 30".replaceAll("\\d+", "**");  // "Name: John, Age: **"

// Remove all non-alphanumeric characters
String clean = "Hello@World#123".replaceAll("[^a-zA-Z0-9]", "");  // "HelloWorld123"

replaceFirst()

Replaces the first substring that matches the given regular expression.

String str = "Hello Hello";
String replaced = str.replaceFirst("Hello", "Hi");  // "Hi Hello"

// Replace first number with #
String text = "The price is 100 and quantity is 200";
String result = text.replaceFirst("\\d+", "#");  // "The price is # and quantity is 200"

Performance Tip

For simple character replacements, replace() is more efficient than replaceAll() as it doesn't use regular expressions.

9. Splitting and Joining

split()

Splits the string around matches of the given regular expression.

// Basic splitting
String str = "apple,orange,banana";
String[] fruits = str.split(",");  // ["apple", "orange", "banana"]

// Limit the number of splits
String data = "one:two:three:four";
String[] parts = data.split(":", 2);  // ["one", "two:three:four"]

// Split on whitespace (one or more spaces)
String text = "Hello   World   Java";
String[] words = text.split("\\s+");  // ["Hello", "World", "Java"]

join() Java 8+

Joins multiple strings with the specified delimiter.

// Join array elements
String[] arr = {"Java", "Python", "JavaScript"};
String joined = String.join(", ", arr);  // "Java, Python, JavaScript"

// Join collection elements
List languages = List.of("Java", "Kotlin", "Scala");
String result = String.join(" | ", languages);  // "Java | Kotlin | Scala"

StringJoiner Java 8+

For more control over joining strings with delimiters, prefixes, and suffixes.

// Basic usage
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("Apple").add("Banana").add("Cherry");
String result = joiner.toString();  // "[Apple, Banana, Cherry]"

// With streams
List names = List.of("John", "Jane", "Jack");
String joined = names.stream()
                   .filter(n -> n.startsWith("J"))
                   .collect(Collectors.joining(", ", "Names: ", ""));
// "Names: John, Jane, Jack"

Performance Consideration

When building large strings from many parts, StringJoiner with Collectors.joining() is more efficient than string concatenation in loops.

10. String Formatting

format() and formatted() Java 15+

Formats strings using format specifiers.

// Basic formatting
String name = "John";
int age = 30;
String message = String.format("Name: %s, Age: %d", name, age);
// "Name: John, Age: 30"

// Format numbers
double price = 19.99;
String priceStr = String.format("Price: $%.2f", price);  // "Price: $19.99"

// Java 15+ formatted() method (instance method)
String greeting = "Hello, %s!".formatted("World");  // "Hello, World!"

// Multi-line formatting
String json = """
    {
        "name": "%s",
        "age": %d,
        "active": %b
    }
""".formatted("John", 30, true);

formatted() Java 15+

Instance method version of String.format() for more fluent code.

String name = "Alice";
String greeting = "Hello, %s!".formatted(name);  // "Hello, Alice!"

// With multiple values
String result = "%s is %d years old".formatted("Bob", 25);  // "Bob is 25 years old"

11. Type Conversion

valueOf()

Converts different types to their string representation.

// Primitive types
String s1 = String.valueOf(100);      // "100"
String s2 = String.valueOf(3.14);     // "3.14"
String s3 = String.valueOf(true);     // "true"

// Object types
String s4 = String.valueOf(new Object());  // calls toString()

// Character array
char[] chars = {'J', 'a', 'v', 'a'};
String s5 = String.valueOf(chars);     // "Java"
String s6 = String.valueOf(chars, 1, 2);  // "av" (offset, count)

toCharArray()

Converts the string to a character array.

String str = "Hello";
char[] chars = str.toCharArray();  // ['H', 'e', 'l', 'l', 'o']

// Common use case: process each character
for (char c : str.toCharArray()) {
    System.out.println(c);
}

getBytes()

Encodes the string into a sequence of bytes using the platform's default charset.

String str = "Hello";
byte[] bytes = str.getBytes();  // Default charset

// Specify charset
byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
byte[] asciiBytes = str.getBytes(StandardCharsets.US_ASCII);

// Convert back to String
String fromBytes = new String(utf8Bytes, StandardCharsets.UTF_8);

12. Pattern Matching (Regex)

matches()

Checks if the string matches the given regular expression.

// Check if string is a number
boolean isNumber = "123".matches("\\d+");  // true

// Email validation
String email = "user@example.com";
boolean isValidEmail = email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");

// Date format validation
String date = "2023-12-31";
boolean isValidDate = date.matches("^\\d{4}-\\d{2}-\\d{2}$");

Pattern and Matcher

For more complex pattern matching operations.

import java.util.regex.*;

String text = "The quick brown fox jumps over the lazy dog";
Pattern pattern = Pattern.compile("\\b\\w{4}\\b");  // 4-letter words
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
    System.out.println(matcher.group());  // "quick", "over", "lazy"
}

// Find and replace
String replaced = text.replaceAll("\\b\\w{4}\\b", "****");
// "The ***** brown fox jumps **** the **** dog"

Regex Performance Tip

For patterns used repeatedly, compile them once with Pattern.compile() and reuse the Pattern instance for better performance.

13. Unicode and Code Points

codePoints() Java 8+

Returns an IntStream of Unicode code points.

String str = "Hello";
int[] codePoints = str.codePoints().toArray();  // [72, 101, 108, 108, 111]

// Count distinct code points
long count = "Hello".codePoints().distinct().count();  // 4

// Convert code points back to String
String fromCodePoints = new String(codePoints, 0, codePoints.length);

offsetByCodePoints()

Returns the index within the string that is offset from the given index by codePointOffset code points.

String str = "A\uD83D\uDE00B";  // A😀B
int index = str.offsetByCodePoints(0, 1);  // 2 (skip the surrogate pair for 😀)

14. Utility Methods

repeat() Java 11+

Returns a string whose value is the concatenation of this string repeated count times.

String str = "-".repeat(5);  // "-----"
String pattern = "* ".repeat(3);  // "* * * "

lines() Java 11+

Returns a stream of lines extracted from the string, separated by line terminators.

String text = "Line 1\nLine 2\r\nLine 3";
long count = text.lines().count();  // 3

// Process lines
text.lines()
    .filter(line -> !line.isBlank())
    .map(String::toUpperCase)
    .forEach(System.out::println);

indent() Java 12+

Adjusts the indentation of each line of the string.

String text = "Hello\nWorld";
String indented = text.indent(4);  // "    Hello\n    World\n"

// Negative values remove indentation
String unindented = indented.indent(-2);  // "  Hello\n  World\n"

transform() Java 12+

Applies a function to the string and returns the result.

String result = "hello"
    .transform(String::toUpperCase)
    .transform(s -> "[" + s + "]");  // "[HELLO]"

// With custom function
String processed = "12345"
    .transform(s -> new StringBuilder(s).reverse().toString())
    .transform(Integer::parseInt);  // 54321

Immutability Reminder

Remember that all String methods return a new string rather than modifying the original, since strings in Java are immutable.

String original = "  Hello  ";
String trimmed = original.trim();
System.out.println(original);  // "  Hello  " (unchanged)
System.out.println(trimmed);   // "Hello" (new string)

String Performance Best Practices

  • Use StringBuilder for multiple string concatenations in loops
  • Pre-compile regex patterns that are used repeatedly
  • Use String.join() or StringJoiner for joining collections
  • Consider using String.intern() for many duplicate strings to save memory
  • Be cautious with substring() in performance-critical code (creates new char[] in Java 7+)

15. Practical Examples and Use Cases

1. Password Strength Checker

public static boolean isPasswordStrong(String password) {
    // At least 8 characters
    if (password == null || password.length() < 8) return false;
    
    // Contains at least one digit
    if (!password.matches(".*\\d.*")) return false;
    
    // Contains at least one lowercase letter
    if (!password.matches(".*[a-z].*")) return false;
    
    // Contains at least one uppercase letter
    if (!password.matches(".*[A-Z].*")) return false;
    
    // Contains at least one special character
    if (!password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) return false;
    
    return true;
}

// Usage
String password = "SecureP@ss123";
boolean isStrong = isPasswordStrong(password);  // true
boolean isStrong = isPasswordStrong(password); // true

2. CSV Parser

public static List<List<String>> parseCSV(String csvData) {
    return csvData.lines()
        .map(line -> {
            // Handle quoted fields with commas
            List<String> fields = new ArrayList<>();
            Pattern pattern = Pattern.compile("\"([^\"]*)\"|([^,\s][^,]*)(?=\s*,|$)");
            Matcher matcher = pattern.matcher(line);
            
            while (matcher.find()) {
                String field = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
                fields.add(field.trim());
            }
            return fields;
        })
        .collect(Collectors.toList());
}

// Usage
String csv = "\"Name\",\"Age\",\"Email\"\n\"John\",30,\"john@example.com\"\nJane,25,jane@example.com";
List<List<String>> data = parseCSV(csv);

3. Text Search with Highlighting

public static String highlightText(String text, String searchTerm) {
    if (text == null || searchTerm == null || searchTerm.isEmpty()) {
        return text;
    }
    
    // Case-insensitive search with word boundaries
    Pattern pattern = Pattern.compile("(?i)(\\b" + Pattern.quote(searchTerm) + "\\b)");
    Matcher matcher = pattern.matcher(text);
    
    // Replace matches with highlighted version
    return matcher.replaceAll("<mark>$1</mark>");
}

// Usage
String content = "The quick brown fox jumps over the lazy dog.";
String highlighted = highlightText(content, "fox");
// "The quick brown <mark>fox</mark> jumps over the lazy dog."

4. URL Parameter Parser

public static Map<String, String> parseUrlParams(String url) {
    Map<String, String> params = new HashMap<>();
    
    try {
        // Extract query string
        String query = new URL(url).getQuery();
        if (query == null) return params;
        
        // Split into key-value pairs
        String[] pairs = query.split("&");
        
        for (String pair : pairs) {
            String[] kv = pair.split("=", 2);
            if (kv.length == 2) {
                String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);
                String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);
                params.put(key, value);
            }
        }
    } catch (Exception e) {
        // Handle invalid URL
    }
    
    return params;
}

// Usage
String url = "https://example.com/search?q=java+tutorial&page=2&sort=recent";
Map<String, String> params = parseUrlParams(url);
// {q=java tutorial, page=2, sort=recent}

5. Text Justification

public static List<String> justifyText(String text, int maxWidth) {
    String[] words = text.trim().split("\\s+");
    List<String> lines = new ArrayList<>();
    StringBuilder currentLine = new StringBuilder();
    
    for (String word : words) {
        if (currentLine.length() + word.length() + 1 <= maxWidth) {
            if (currentLine.length() > 0) {
                currentLine.append(" ");
            }
            currentLine.append(word);
        } else {
            lines.add(justifyLine(currentLine.toString(), maxWidth));
            currentLine = new StringBuilder(word);
        }
    }
    
    if (currentLine.length() > 0) {
        lines.add(currentLine.toString());
    }
    
    return lines;
}

private static String justifyLine(String line, int maxWidth) {
    if (line.isEmpty()) return "".repeat(maxWidth);
    
    String[] words = line.split(" ");
    if (words.length == 1) {
        return String.format("%-" + maxWidth + "s", line);
    }
    
    int totalSpaces = maxWidth - line.replace(" ", "").length();
    int gaps = words.length - 1;
    int baseSpaces = totalSpaces / gaps;
    int extraSpaces = totalSpaces % gaps;
    
    StringBuilder justified = new StringBuilder(words[0]);
    for (int i = 1; i < words.length; i++) {
        int spaces = baseSpaces + (i <= extraSpaces ? 1 : 0);
        justified.append(" ".repeat(spaces)).append(words[i]);
    }
    
    return justified.toString();
}

// Usage
String text = "This is a sample text that needs to be justified to a specific width.";
List<String> justified = justifyText(text, 20);
// ["This   is   a  sample", "text that needs to be", "justified  to   a", "specific     width."]

Real-world Considerations

When working with strings in production code, consider these aspects:

  • Input Validation: Always validate and sanitize string inputs
  • Internationalization: Be aware of Unicode and locale-specific string handling
  • Performance: For heavy string manipulation, consider using StringBuilder or StringBuffer
  • Security: Be cautious with string operations in security-sensitive contexts (e.g., SQL, HTML, file paths)
  • Memory Usage: Large strings can consume significant memory; process in chunks when possible