Common String Methods in Java

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

CategoryKey MethodsUse Cases
Inspectionlength(), isEmpty(), isBlank()Validation, checking
Comparisonequals(), compareTo(), contains()Sorting, searching
SearchingindexOf(), lastIndexOf(), charAt()Text analysis
Extractionsubstring(), split()Data parsing
Modificationreplace(), toUpperCase(), trim()Data cleaning
Advancedchars(), lines(), transform()Modern processing

Best Practices

  1. Always check for null before calling string methods
  2. Use equals() for content comparison, not ==
  3. Prefer isBlank() over isEmpty() for whitespace checking
  4. Use StringBuilder for multiple string modifications
  5. Cache frequently used strings to avoid duplication
  6. Use regular expressions wisely - they can be performance-intensive
  7. 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
  • StringBuilder is 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!

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper