Java String.trim
Remove leading and trailing characters whose value is at most U+0020.
A simple example
String.trim
- Start with " A "
- Do this Remove surrounding spaces
- Result "A"
Syntax
public String trim()
JDK 21 method signatures (1)
public String trim()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaClean padding from a classroom code
A user pastes a name or code from another application. Remove the unwanted outer padding while preserving the spaces and letters that belong to the actual value.
class Main {
public static void main(String[] args) throws Exception {
String code = " CS 101 ";
System.out.println(code.trim());
}
}
CS 101
The space between the subject and number is retained.
Check the boundary of legacy trimming
An older import includes padding around a fixed-width label. Compare the characters actually removed by the chosen trimming operation, since a visible margin can contain more than an ordinary space.
class Main {
public static void main(String[] args) throws Exception {
String label = "\u2003tea\u2003";
System.out.println(label.trim().length());
}
}
5
An em space is above U+0020, so neither end is removed.
Clean a course import
A course name arrives padded on both sides. Remove leading and trailing ASCII spaces before placing the text between the display brackets.
What to watch for
Use strip for Java whitespace beyond the older trim range. Interior spaces are preserved.