allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œBlessed is the one who trusts in the Lord, whose confidence is in him.โ€
[Jeremiah 17:7]


String Methods


16.2.1 Core Methods You Must Master

Working with strings isnโ€™t just about storing text โ€” itโ€™s about manipulating and analyzing it.
Javaโ€™s String class has dozens of built-in methods. The core ones appear in every project:

MethodWhat it does
length()Number of characters
charAt(index)Get a single character
substring(start, end)Get part of the string
indexOf(substring)Find first position
toUpperCase()Make all uppercase
toLowerCase()Make all lowercase
trim()Remove leading/trailing spaces
replace()Replace part of the text
split()Break into parts by delimiter

When does this matter?

  • Input validation: Trim spaces, check length, extract parts.

  • Parsing: Parse CSV, JSON, query strings.

  • Transforming: Change case for usernames or slug URLs.

  • Search: Find keywords inside text.

  • Replace: Censor bad words, change placeholders, etc.



16.2.2 Mini Lab: Real-World String Processing

Below is an expanded practical Mini Lab with multiple everyday operations.

java
public class StringMethodsMiniLab { public static void main(String[] args) { String input = " Hello, Java Web Developer! "; System.out.println("Original: [" + input + "]"); System.out.println("Length: " + input.length()); System.out.println("Char at index 7: " + input.charAt(7)); System.out.println("Substring (7-10): " + input.substring(7, 10)); System.out.println("Index of 'Java': " + input.indexOf("Java")); System.out.println("Uppercase: " + input.toUpperCase()); System.out.println("Lowercase: " + input.toLowerCase()); System.out.println("Trimmed: [" + input.trim() + "]"); System.out.println("Replaced: " + input.replace("Java", "Spring")); // Splitting String csv = "apple,banana,cherry"; String[] fruits = csv.split(","); for (String fruit : fruits) { System.out.println("Fruit: " + fruit.trim()); } } }

New pieces here:

  • split() breaks a string into an array.

  • trim() is critical for clean input.

  • replace() swaps parts dynamically โ€” e.g., replacing a tech name in a template.

  • indexOf() helps you find positions for parsing or highlighting.


โœ… Pro tip for real projects:
Never trust user input blindly. Use trim(), toLowerCase(), and replace() to sanitize, normalize, and clean it before saving to a database.