Java String.strip and isBlank
Use strip to remove whitespace at the ends of a name. Use isBlank to recognize an empty field or one made entirely of Java whitespace.
A simple example
String.strip and isBlank
- Start with " A "
- Do this Remove surrounding spaces
- Result "A"
class Main {
public static void main(String[] args) throws Exception {
System.out.println(" A ".strip());
}
}
A
Syntax
name.strip()
name.isBlank()
JDK 21 method signatures (2)
public String strip()
public boolean isBlank()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint a name tag
A printer receives badge or ticket data in separate fields. Use the display format required by the desk so names, numbers and separators occupy their intended places on the finished label.
public class Main {
public static void main(String[] args) throws Exception {
for (String name : new String[]{" Ana Lee ", " "}) {
System.out.println(name.isBlank() ? "Guest" : name.strip());
}
}
}
Ana Lee Guest
Ana’s first and last name keep their internal space. The second entry contains only spaces, so its name tag says Guest.
Flag a whitespace-only assignment
A form can look blank even when its field contains a space. Examine the stored input before marking the answer as missing, because an empty string and whitespace can require separate checks.
class Main {
public static void main(String[] args) throws Exception {
String submission = " \t ";
System.out.println(submission.isBlank());
}
}
true
Spaces and a tab do not supply an answer.
Accept a meaningful booking note
A form accepts an optional note typed or pasted by a customer or student. Decide whether the field contains meaningful text before displaying it to the person who will act on the request.
class Main {
public static void main(String[] args) throws Exception {
String note = " aisle seat ";
System.out.println(note.isBlank());
}
}
false
The words between the spaces make the note meaningful.
Clean a pasted book title
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 book = "\u2003Data Basics\t";
System.out.println(book.strip());
}
}
Data Basics
Both the leading em space and the final tab are removed.
Handle an empty ticket field
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
class Main {
public static void main(String[] args) throws Exception {
String field = " \t ";
System.out.println(field.strip().length());
}
}
0
The field contains only removable whitespace.
What to watch for
Spaces between words remain. A null reference needs its own check before either instance method can be called.