String Methods
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:
| Method | What 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.
Below is an expanded practical Mini Lab with multiple everyday operations.
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.