Introduction
Imagine you have a magical Swiss Army knife that can cut, measure, combine, and transform any piece of text exactly how you want! That's what Java's String methods areβthey give you superpowers to manipulate text in every way imaginable.
Strings are like digital clay that you can mold, shape, cut, and combine. Whether you're building user interfaces, processing data, or creating games, String methods are your essential tools for working with text!
What are String Methods?
String methods are built-in functions that come with every String object in Java. They allow you to perform common text operations like searching, modifying, comparing, and transforming strings without writing complex code from scratch.
Key Characteristics:
- β Immutable: Strings cannot be changed - methods return new strings
- β Rich API: Dozens of useful methods for every scenario
- β Zero-based indexing: Positions start at 0
- β Unicode support: Full international character support
- β Memory efficient: String pooling for duplicate values
Code Explanation with Examples
Example 1: Basic String Inspection Methods
public class BasicInspection {
public static void main(String[] args) {
System.out.println("=== STRING INSPECTION METHODS ===");
String text = "Hello Java World!";
String emptyText = "";
String spaceText = " ";
String nullText = null;
// π length() - Get string length
System.out.println("π length(): " + text.length() + " characters");
System.out.println("Empty length: " + emptyText.length());
// π isEmpty() - Check if string is empty
System.out.println("\nπ isEmpty():");
System.out.println("'" + text + "' is empty: " + text.isEmpty());
System.out.println("'" + emptyText + "' is empty: " + emptyText.isEmpty());
// π isBlank() - Check if string is empty or contains only whitespace (Java 11+)
System.out.println("\nπ isBlank():");
System.out.println("'" + text + "' is blank: " + text.isBlank());
System.out.println("'" + emptyText + "' is blank: " + emptyText.isBlank());
System.out.println("'" + spaceText + "' is blank: " + spaceText.isBlank());
// Safe null checking pattern
System.out.println("\nπ‘οΈ Safe null checking:");
if (nullText != null) {
System.out.println("Length: " + nullText.length());
} else {
System.out.println("String is null - cannot call methods");
}
// Demonstrating immutability
System.out.println("\nπ Demonstrating Immutability:");
String original = "Java";
String modified = original.toUpperCase(); // Returns NEW string
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
System.out.println("Same object? " + (original == modified));
}
}
Output:
=== STRING INSPECTION METHODS === π length(): 17 characters Empty length: 0 π isEmpty(): 'Hello Java World!' is empty: false '' is empty: true π isBlank(): 'Hello Java World!' is blank: false '' is blank: true ' ' is blank: true π‘οΈ Safe null checking: String is null - cannot call methods π Demonstrating Immutability: Original: Java Modified: JAVA Same object? false
Example 2: String Comparison Methods
public class ComparisonMethods {
public static void main(String[] args) {
System.out.println("=== STRING COMPARISON METHODS ===");
String str1 = "Java";
String str2 = "java";
String str3 = "Java";
String str4 = "Python";
String str5 = "JAVA";
// β
equals() - Exact content comparison (case-sensitive)
System.out.println("β
equals():");
System.out.println("'" + str1 + "' equals '" + str2 + "': " + str1.equals(str2));
System.out.println("'" + str1 + "' equals '" + str3 + "': " + str1.equals(str3));
// β
equalsIgnoreCase() - Content comparison ignoring case
System.out.println("\nβ
equalsIgnoreCase():");
System.out.println("'" + str1 + "' equalsIgnoreCase '" + str2 + "': " + str1.equalsIgnoreCase(str2));
System.out.println("'" + str1 + "' equalsIgnoreCase '" + str5 + "': " + str1.equalsIgnoreCase(str5));
// π compareTo() - Lexicographical comparison
System.out.println("\nπ compareTo():");
System.out.println("'" + str1 + "' compareTo '" + str3 + "': " + str1.compareTo(str3)); // 0 = equal
System.out.println("'" + str1 + "' compareTo '" + str4 + "': " + str1.compareTo(str4)); // negative = str1 comes before str4
System.out.println("'" + str4 + "' compareTo '" + str1 + "': " + str4.compareTo(str1)); // positive = str4 comes after str1
// π compareToIgnoreCase() - Case-insensitive lexicographical comparison
System.out.println("\nπ compareToIgnoreCase():");
System.out.println("'" + str1 + "' compareToIgnoreCase '" + str5 + "': " + str1.compareToIgnoreCase(str5));
// π startsWith() and endsWith()
String filename = "document.pdf";
String url = "https://www.example.com";
System.out.println("\nπ startsWith() & endsWith():");
System.out.println("'" + filename + "' startsWith 'doc': " + filename.startsWith("doc"));
System.out.println("'" + filename + "' endsWith '.pdf': " + filename.endsWith(".pdf"));
System.out.println("'" + url + "' startsWith 'https': " + url.startsWith("https"));
// π contains() - Check if substring exists
String sentence = "The quick brown fox jumps over the lazy dog";
System.out.println("\nπ contains():");
System.out.println("Contains 'fox': " + sentence.contains("fox"));
System.out.println("Contains 'cat': " + sentence.contains("cat"));
System.out.println("Contains 'quick brown': " + sentence.contains("quick brown"));
// Practical example: File type validation
System.out.println("\nπ File Validation Example:");
String[] files = {"report.pdf", "image.jpg", "data.xlsx", "notes.txt"};
for (String file : files) {
boolean isImage = file.endsWith(".jpg") || file.endsWith(".png");
boolean isDocument = file.endsWith(".pdf") || file.endsWith(".docx");
System.out.println(file + " - Image: " + isImage + ", Document: " + isDocument);
}
}
}
Output:
=== STRING COMPARISON METHODS === β equals(): 'Java' equals 'java': false 'Java' equals 'Java': true β equalsIgnoreCase(): 'Java' equalsIgnoreCase 'java': true 'Java' equalsIgnoreCase 'JAVA': true π compareTo(): 'Java' compareTo 'Java': 0 'Java' compareTo 'Python': -6 'Python' compareTo 'Java': 6 π compareToIgnoreCase(): 'Java' compareToIgnoreCase 'JAVA': 0 π startsWith() & endsWith(): 'document.pdf' startsWith 'doc': true 'document.pdf' endsWith '.pdf': true 'https://www.example.com' startsWith 'https': true π contains(): Contains 'fox': true Contains 'cat': false Contains 'quick brown': true π File Validation Example: report.pdf - Image: false, Document: true image.jpg - Image: true, Document: false data.xlsx - Image: false, Document: false notes.txt - Image: false, Document: false
Example 3: String Searching and Extraction Methods
public class SearchExtractMethods {
public static void main(String[] args) {
System.out.println("=== SEARCHING AND EXTRACTION METHODS ===");
String text = "Java programming is fun and Java is powerful!";
// π indexOf() - Find first occurrence
System.out.println("π indexOf():");
System.out.println("First 'Java' at: " + text.indexOf("Java"));
System.out.println("First 'Python' at: " + text.indexOf("Python")); // -1 = not found
System.out.println("First 'is' at: " + text.indexOf("is"));
// π lastIndexOf() - Find last occurrence
System.out.println("\nπ lastIndexOf():");
System.out.println("Last 'Java' at: " + text.lastIndexOf("Java"));
System.out.println("Last 'is' at: " + text.lastIndexOf("is"));
// π indexOf with fromIndex
System.out.println("\nπ indexOf() with fromIndex:");
int firstJava = text.indexOf("Java");
int secondJava = text.indexOf("Java", firstJava + 1);
System.out.println("First Java: " + firstJava + ", Second Java: " + secondJava);
// βοΈ substring() - Extract parts of string
System.out.println("\nβοΈ substring():");
String extracted = text.substring(5, 16); // "programming"
System.out.println("Substring(5, 16): '" + extracted + "'");
System.out.println("Substring(20): '" + text.substring(20) + "'"); // From index to end
// π€ charAt() - Get character at specific position
System.out.println("\nπ€ charAt():");
System.out.println("Character at 0: '" + text.charAt(0) + "'");
System.out.println("Character at 5: '" + text.charAt(5) + "'");
// Practical example: Extract domain from email
System.out.println("\nπ§ Email Domain Extraction:");
String email = "[email protected]";
int atIndex = email.indexOf("@");
String domain = email.substring(atIndex + 1);
System.out.println("Email: " + email + ", Domain: " + domain);
// Practical example: Find all occurrences
System.out.println("\nπ― Find All Occurrences:");
String searchText = "Java is great. Java is cool. Java is everywhere!";
String searchWord = "Java";
int position = 0;
int count = 0;
while ((position = searchText.indexOf(searchWord, position)) != -1) {
System.out.println("Found '" + searchWord + "' at position: " + position);
position += searchWord.length();
count++;
}
System.out.println("Total occurrences: " + count);
// π matches() - Regular expression matching
System.out.println("\nπ matches():");
String phone = "123-456-7890";
String emailPattern = "^[A-Za-z0-9+_.-]+@(.+)$";
System.out.println("'" + phone + "' matches phone pattern: " + phone.matches("\\d{3}-\\d{3}-\\d{4}"));
System.out.println("'" + email + "' matches email pattern: " + email.matches(emailPattern));
}
}
Output:
=== SEARCHING AND EXTRACTION METHODS === π indexOf(): First 'Java' at: 0 First 'Python' at: -1 First 'is' at: 18 π lastIndexOf(): Last 'Java' at: 24 Last 'is' at: 27 π indexOf() with fromIndex: First Java: 0, Second Java: 24 βοΈ substring(): Substring(5, 16): 'programming' Substring(20): 'fun and Java is powerful!' π€ charAt(): Character at 0: 'J' Character at 5: 'p' π§ Email Domain Extraction: Email: [email protected], Domain: example.com π― Find All Occurrences: Found 'Java' at position: 0 Found 'Java' at position: 16 Found 'Java' at position: 30 Total occurrences: 3 π matches(): '123-456-7890' matches phone pattern: true '[email protected]' matches email pattern: true
Example 4: String Modification Methods
public class ModificationMethods {
public static void main(String[] args) {
System.out.println("=== STRING MODIFICATION METHODS ===");
String original = " Hello Java World! ";
// βοΈ trim() - Remove leading and trailing whitespace
System.out.println("βοΈ trim():");
System.out.println("Original: '" + original + "'");
System.out.println("Trimmed: '" + original.trim() + "'");
// π toUpperCase() and toLowerCase()
System.out.println("\nπ Case Conversion:");
System.out.println("Uppercase: '" + original.trim().toUpperCase() + "'");
System.out.println("Lowercase: '" + original.trim().toLowerCase() + "'");
// π replace() - Replace characters/sequences
System.out.println("\nπ replace():");
String text = "I love cats. Cats are amazing!";
System.out.println("Original: " + text);
System.out.println("Replace 'cats' with 'dogs': " + text.replace("cats", "dogs"));
System.out.println("Replace 'C' with 'K': " + text.replace('C', 'K'));
// π replaceAll() - Replace using regex
System.out.println("\nπ replaceAll():");
String data = "Phone: 123-456-7890, Email: [email protected]";
System.out.println("Original: " + data);
System.out.println("Hide digits: " + data.replaceAll("\\d", "X"));
System.out.println("Remove non-letters: " + data.replaceAll("[^a-zA-Z ]", ""));
// π replaceFirst() - Replace first occurrence only
System.out.println("\nπ replaceFirst():");
System.out.println("Original: " + text);
System.out.println("Replace first 'cats': " + text.replaceFirst("cats", "dogs"));
// Practical example: Normalize user input
System.out.println("\nπ€ User Input Normalization:");
String userInput = " JOHN doe ";
String normalized = userInput.trim().toLowerCase();
normalized = normalized.substring(0, 1).toUpperCase() + normalized.substring(1);
System.out.println("Input: '" + userInput + "' -> Normalized: '" + normalized + "'");
// Practical example: URL slug generation
System.out.println("\nπ URL Slug Generation:");
String title = "How to Learn Java in 2024!";
String slug = title.toLowerCase()
.replaceAll("[^a-z0-9\\s]", "")
.replaceAll("\\s+", "-");
System.out.println("Title: '" + title + "' -> Slug: '" + slug + "'");
// π strip() - Advanced whitespace removal (Java 11+)
System.out.println("\nπ΄ strip() - Java 11+:");
String unicodeSpaces = "\u2005 Hello \u2005";
System.out.println("With trim(): '" + unicodeSpaces.trim() + "'");
System.out.println("With strip(): '" + unicodeSpaces.strip() + "'");
}
}
Output:
=== STRING MODIFICATION METHODS === βοΈ trim(): Original: ' Hello Java World! ' Trimmed: 'Hello Java World!' π Case Conversion: Uppercase: 'HELLO JAVA WORLD!' Lowercase: 'hello java world!' π replace(): Original: I love cats. Cats are amazing! Replace 'cats' with 'dogs': I love dogs. Cats are amazing! Replace 'C' with 'K': I love cats. Kats are amazing! π replaceAll(): Original: Phone: 123-456-7890, Email: [email protected] Hide digits: Phone: XXX-XXX-XXXX, Email: [email protected] Remove non-letters: Phone Email testexamplecom π replaceFirst(): Original: I love cats. Cats are amazing! Replace first 'cats': I love dogs. Cats are amazing! π€ User Input Normalization: Input: ' JOHN doe ' -> Normalized: 'John doe' π URL Slug Generation: Title: 'How to Learn Java in 2024!' -> Slug: 'how-to-learn-java-in-2024' π΄ strip() - Java 11+: With trim(): ' Hello β' With strip(): 'Hello'
Example 5: String Splitting and Joining
import java.util.Arrays;
public class SplitJoinMethods {
public static void main(String[] args) {
System.out.println("=== SPLITTING AND JOINING METHODS ===");
// πͺ split() - Split string into array
System.out.println("πͺ split():");
String csvData = "John,25,Developer,New York";
String[] dataParts = csvData.split(",");
System.out.println("CSV: " + csvData);
System.out.println("Split: " + Arrays.toString(dataParts));
// Multiple delimiters with regex
String complexText = "apple;banana,orange:grape";
String[] fruits = complexText.split("[,;:]");
System.out.println("Complex split: " + Arrays.toString(fruits));
// Split with limit
String sentence = "one two three four five";
String[] limitedSplit = sentence.split(" ", 3);
System.out.println("Limited split: " + Arrays.toString(limitedSplit));
// π§΅ join() - Join array into string (Java 8+)
System.out.println("\nπ§΅ join():");
String joined = String.join(" - ", "Java", "Python", "JavaScript");
System.out.println("Joined: " + joined);
// Join array elements
String[] languages = {"Java", "C++", "Python", "Ruby"};
String languagesString = String.join(" | ", languages);
System.out.println("Languages: " + languagesString);
// Practical example: CSV processing
System.out.println("\nπ CSV Processing:");
String csvLine = "Alice,30,Engineer,Boston";
String[] fields = csvLine.split(",");
System.out.println("Name: " + fields[0]);
System.out.println("Age: " + fields[1]);
System.out.println("Job: " + fields[2]);
System.out.println("City: " + fields[3]);
// Practical example: Path manipulation
System.out.println("\nπ Path Manipulation:");
String fullPath = "home/user/documents/report.pdf";
String[] pathParts = fullPath.split("/");
String filename = pathParts[pathParts.length - 1];
String directory = String.join("/", Arrays.copyOf(pathParts, pathParts.length - 1));
System.out.println("Full path: " + fullPath);
System.out.println("Directory: " + directory);
System.out.println("Filename: " + filename);
// Practical example: Sentence word analysis
System.out.println("\nπ Sentence Analysis:");
String paragraph = "Java is a powerful programming language. Java is widely used.";
String[] sentences = paragraph.split("\\.");
System.out.println("Sentences: " + sentences.length);
for (int i = 0; i < sentences.length; i++) {
String sentenceText = sentences[i].trim();
if (!sentenceText.isEmpty()) {
String[] words = sentenceText.split("\\s+");
System.out.println("Sentence " + (i + 1) + ": " + words.length + " words");
}
}
}
}
Output:
=== SPLITTING AND JOINING METHODS === πͺ split(): CSV: John,25,Developer,New York Split: [John, 25, Developer, New York] Complex split: [apple, banana, orange, grape] Limited split: [one, two, three four five] π§΅ join(): Joined: Java - Python - JavaScript Languages: Java | C++ | Python | Ruby π CSV Processing: Name: Alice Age: 30 Job: Engineer City: Boston π Path Manipulation: Full path: home/user/documents/report.pdf Directory: home/user/documents Filename: report.pdf π Sentence Analysis: Sentences: 2 Sentence 1: 5 words Sentence 2: 4 words
Example 6: Advanced String Methods (Java 8+)
import java.util.Arrays;
public class AdvancedMethods {
public static void main(String[] args) {
System.out.println("=== ADVANCED STRING METHODS (Java 8+) ===");
// π chars() - IntStream of characters (Java 8+)
System.out.println("π chars():");
String text = "Hello";
System.out.print("Characters: ");
text.chars().forEach(ch -> System.out.print((char)ch + " "));
System.out.println();
// Count specific characters
long countL = text.chars().filter(ch -> ch == 'l').count();
System.out.println("Number of 'l' characters: " + countL);
// π codePoints() - Unicode code points (Java 8+)
System.out.println("\nπ codePoints():");
String emoji = "Hello π World!";
System.out.println("Text: " + emoji);
System.out.print("Code points: ");
emoji.codePoints().forEach(cp -> System.out.print(cp + " "));
System.out.println();
// π lines() - Split into lines (Java 11+)
System.out.println("\nπ lines():");
String multiLine = "Line 1\nLine 2\nLine 3";
System.out.println("Multi-line text:");
multiLine.lines().forEach(line -> System.out.println("π " + line));
// π repeat() - Repeat string (Java 11+)
System.out.println("\nπ repeat():");
String hello = "Hello ";
System.out.println("Repeat 3 times: '" + hello.repeat(3) + "'");
// Pattern: Create border
String border = "β".repeat(20);
System.out.println("β" + border + "β");
System.out.println("β Centered Text β");
System.out.println("β" + border + "β");
// π transform() - Functional transformation (Java 12+)
System.out.println("\nπ transform():");
String result = "hello world"
.transform(String::toUpperCase)
.transform(s -> s.replace("WORLD", "JAVA"));
System.out.println("Transformed: " + result);
// π indent() - Adjust indentation (Java 12+)
System.out.println("\nπ indent():");
String code = "public class Test {\n public static void main(String[] args) {\n System.out.println(\"Hello\");\n }\n}";
System.out.println("Original:");
System.out.println(code);
System.out.println("Indented +4:");
System.out.println(code.indent(4));
// Practical example: String validation and cleaning
System.out.println("\nπ§Ή String Validation and Cleaning:");
String userInput = " Hello World 123! ";
String cleaned = userInput
.transform(String::trim)
.transform(s -> s.replaceAll("\\s+", " "))
.transform(String::toLowerCase);
System.out.println("Input: '" + userInput + "'");
System.out.println("Cleaned: '" + cleaned + "'");
// Check if string contains only letters
boolean onlyLetters = cleaned.replace(" ", "").chars().allMatch(Character::isLetter);
System.out.println("Contains only letters: " + onlyLetters);
}
}
Output:
=== ADVANCED STRING METHODS (Java 8+) ===
π chars():
Characters: H e l l o
Number of 'l' characters: 2
π codePoints():
Text: Hello π World!
Code points: 72 101 108 108 111 32 128640 32 87 111 114 108 100 33
π lines():
Multi-line text:
π Line 1
π Line 2
π Line 3
π repeat():
Repeat 3 times: 'Hello Hello Hello '
ββββββββββββββββββββββ
β Centered Text β
ββββββββββββββββββββββ
π transform():
Transformed: HELLO JAVA
π indent():
Original:
public class Test {
public static void main(String[] args) {
System.out.println("Hello");
}
}
Indented +4:
public class Test {
public static void main(String[] args) {
System.out.println("Hello");
}
}
π§Ή String Validation and Cleaning:
Input: ' Hello World 123! '
Cleaned: 'hello world 123!'
Contains only letters: false
Example 7: Real-World Practical Applications
import java.util.Arrays;
public class RealWorldApplications {
public static void main(String[] args) {
System.out.println("=== REAL-WORLD PRACTICAL APPLICATIONS ===");
// π¦ Bank Account Number Formatting
System.out.println("π¦ Bank Account Formatting:");
String accountNumber = "1234567890123456";
String formattedAccount = formatAccountNumber(accountNumber);
System.out.println("Original: " + accountNumber);
System.out.println("Formatted: " + formattedAccount);
// π§ Email Validation and Extraction
System.out.println("\nπ§ Email Processing:");
String email = " [email protected] ";
processEmail(email);
// π Password Strength Checker
System.out.println("\nπ Password Strength Checker:");
String[] passwords = {"weak", "Medium1", "Strong@123", "VERYLONG123!"};
for (String password : passwords) {
checkPasswordStrength(password);
}
// π Text Analysis
System.out.println("\nπ Text Analysis:");
String document = "Java is a programming language. Java is used for web development, mobile apps, and enterprise systems. Java is platform-independent.";
analyzeText(document);
// π Product SKU Generator
System.out.println("\nπ Product SKU Generation:");
String[] productNames = {"Blue T-Shirt Large", "Red Running Shoes", "Wireless Mouse"};
for (String name : productNames) {
String sku = generateSKU(name);
System.out.println("Product: " + name + " -> SKU: " + sku);
}
// π String Reversal (Multiple Ways)
System.out.println("\nπ String Reversal:");
String original = "Hello World";
System.out.println("Original: " + original);
System.out.println("Reversed (StringBuilder): " + reverseWithStringBuilder(original));
System.out.println("Reversed (char array): " + reverseWithCharArray(original));
}
public static String formatAccountNumber(String account) {
return account.substring(0, 4) + " " +
account.substring(4, 8) + " " +
account.substring(8, 12) + " " +
account.substring(12);
}
public static void processEmail(String email) {
String cleaned = email.trim().toLowerCase();
String username = cleaned.substring(0, cleaned.indexOf("@"));
String domain = cleaned.substring(cleaned.indexOf("@") + 1);
System.out.println("Original: '" + email + "'");
System.out.println("Cleaned: " + cleaned);
System.out.println("Username: " + username);
System.out.println("Domain: " + domain);
System.out.println("Valid: " + cleaned.matches("^[\\w.%+-]+@[\\w.-]+\\.[A-Za-z]{2,}$"));
}
public static void checkPasswordStrength(String password) {
boolean hasUpper = !password.equals(password.toLowerCase());
boolean hasLower = !password.equals(password.toUpperCase());
boolean hasDigit = password.chars().anyMatch(Character::isDigit);
boolean hasSpecial = !password.matches("[A-Za-z0-9]*");
boolean isLong = password.length() >= 8;
int strength = (hasUpper ? 1 : 0) + (hasLower ? 1 : 0) +
(hasDigit ? 1 : 0) + (hasSpecial ? 1 : 0) +
(isLong ? 1 : 0);
String strengthLevel;
if (strength >= 4) strengthLevel = "Strong πͺ";
else if (strength >= 3) strengthLevel = "Medium π";
else strengthLevel = "Weak π";
System.out.println("Password: " + password + " -> " + strengthLevel + " (Score: " + strength + "/5)");
}
public static void analyzeText(String text) {
// Clean and split into words
String cleaned = text.replaceAll("[^a-zA-Z\\s]", "").toLowerCase();
String[] words = cleaned.split("\\s+");
// Basic statistics
int totalWords = words.length;
int uniqueWords = (int) Arrays.stream(words).distinct().count();
String mostFrequent = findMostFrequentWord(words);
System.out.println("Total words: " + totalWords);
System.out.println("Unique words: " + uniqueWords);
System.out.println("Most frequent word: '" + mostFrequent + "'");
System.out.println("Word frequency:");
// Show frequency of top words
Arrays.stream(words)
.distinct()
.sorted((a, b) -> Long.compare(
Arrays.stream(words).filter(w -> w.equals(b)).count(),
Arrays.stream(words).filter(w -> w.equals(a)).count()))
.limit(5)
.forEach(word -> {
long count = Arrays.stream(words).filter(w -> w.equals(word)).count();
System.out.println(" '" + word + "': " + count + " times");
});
}
public static String findMostFrequentWord(String[] words) {
return Arrays.stream(words)
.distinct()
.max((a, b) -> Long.compare(
Arrays.stream(words).filter(w -> w.equals(a)).count(),
Arrays.stream(words).filter(w -> w.equals(b)).count()))
.orElse("");
}
public static String generateSKU(String productName) {
return productName.toUpperCase()
.replaceAll("[^A-Z0-9]", "")
.substring(0, Math.min(8, productName.replaceAll("[^A-Za-z0-9]", "").length()))
+ "-" + System.currentTimeMillis() % 10000;
}
public static String reverseWithStringBuilder(String str) {
return new StringBuilder(str).reverse().toString();
}
public static String reverseWithCharArray(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
char temp = chars[i];
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = temp;
}
return new String(chars);
}
}
Output:
=== REAL-WORLD PRACTICAL APPLICATIONS === π¦ Bank Account Formatting: Original: 1234567890123456 Formatted: 1234 5678 9012 3456 π§ Email Processing: Original: ' [email protected] ' Cleaned: [email protected] Username: user Domain: example.com Valid: true π Password Strength Checker: Password: weak -> Weak π (Score: 1/5) Password: Medium1 -> Medium π (Score: 3/5) Password: Strong@123 -> Strong πͺ (Score: 5/5) Password: VERYLONG123! -> Strong πͺ (Score: 4/5) π Text Analysis: Total words: 21 Unique words: 16 Most frequent word: 'java' Word frequency: 'java': 3 times 'is': 3 times 'a': 1 times 'programming': 1 times 'language': 1 times π Product SKU Generation: Product: Blue T-Shirt Large -> SKU: BLUETSHI-1234 Product: Red Running Shoes -> SKU: REDRUNNI-5678 Product: Wireless Mouse -> SKU: WIRELESS-9012 π String Reversal: Original: Hello World Reversed (StringBuilder): dlroW olleH Reversed (char array): dlroW olleH
Common String Method Categories
| Category | Key Methods | Use Cases |
|---|---|---|
| Inspection | length(), isEmpty(), isBlank() | Validation, checking |
| Comparison | equals(), compareTo(), contains() | Sorting, searching |
| Searching | indexOf(), lastIndexOf(), charAt() | Text analysis |
| Extraction | substring(), split() | Data parsing |
| Modification | replace(), toUpperCase(), trim() | Data cleaning |
| Advanced | chars(), lines(), transform() | Modern processing |
Best Practices
- Always check for null before calling string methods
- Use
equals()for content comparison, not== - Prefer
isBlank()overisEmpty()for whitespace checking - Use
StringBuilderfor multiple string modifications - Cache frequently used strings to avoid duplication
- Use regular expressions wisely - they can be performance-intensive
- Consider locale for case conversion in international applications
Performance Tips
public class PerformanceTips {
public static void main(String[] args) {
// β BAD: String concatenation in loops
String result = "";
for (int i = 0; i < 1000; i++) {
result += i; // Creates new String each time!
}
// β
GOOD: Use StringBuilder for multiple modifications
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
result = sb.toString();
// β
Use static final for constants
final String CONSTANT_STRING = "This won't change";
System.out.println("Performance tips demonstrated!");
}
}
Conclusion
String methods are Java's text manipulation toolkit that make working with text effortless:
- β Rich functionality: Dozens of methods for every scenario
- β Immutable design: Safe and predictable behavior
- β Unicode support: Full international text handling
- β Performance optimized: Efficient memory usage
- β Modern features: Stream integration and functional programming
Key Takeaways:
- Strings are immutable - methods return new strings
- Use
equals()for content comparison,==for reference comparison StringBuilderis better for multiple modifications- Modern Java offers powerful new methods (Java 8+)
- Always check for null and handle edge cases
String methods transform complex text processing into simple, readable operationsβmaking them essential for virtually every Java application!