String Methods
String provides methods for inspecting and transforming text.
| Method | What it does |
|---|---|
length() | Counts the characters |
isEmpty() | Checks whether the length is 0 |
trim() | Removes spaces at both ends |
toUpperCase() | Returns an uppercase string |
startsWith(text) | Checks the beginning of a string |
substring(start, end) | Returns part of a string |
replace(old, new) | Replaces matching text |
These methods return new strings. The original string does not change because String objects are immutable.
Clean and inspect text
public class Main {
public static void main(String[] args) {
String raw = " compile ";
String cleaned = raw.trim().toUpperCase();
System.out.println(cleaned);
System.out.println(cleaned.startsWith("COM"));
System.out.println(cleaned.length());
System.out.println("".isEmpty());
}
}
Output:
COMPILE
true
7
true
Outer spaces are removed before case normalization, making the prefix check consistent. The cleaned text has seven characters, and "" is an empty string.
Trim the message, convert it to uppercase, and check whether it starts with ERR.