Practical Examples
Real-World Scenarios for String Validation
public class UserRegistration {
public boolean validateUsername(String username) {
return username != null && !username.trim().isEmpty();
}
}
public class FormValidator {
public boolean isValidForm(String name, String email, String password) {
return !(name == null || name.trim().isEmpty() ||
email == null || email.trim().isEmpty() ||
password == null || password.isEmpty());
}
}
Validation Workflow
graph TD
A[Input Received] --> B{Null Check}
B -->|Null| C[Reject]
B -->|Not Null| D{Trim Check}
D -->|Empty After Trim| E[Reject]
D -->|Has Content| F[Accept]
Common Validation Patterns
Scenario |
Validation Method |
Example |
Username |
Trim + Length Check |
username.trim().length() >= 3 |
Email |
Regex + Empty Check |
email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}") |
Password |
Not Empty + Complexity |
password.length() >= 8 && containsSpecialChar(password) |
3. Configuration Parameter Checking
public class ConfigurationManager {
public void loadConfiguration(String configPath) {
if (configPath == null || configPath.trim().isEmpty()) {
throw new IllegalArgumentException("Configuration path cannot be empty");
}
// Load configuration logic
}
}
4. Database Query Parameter Validation
public class DatabaseService {
public List<User> searchUsers(String searchTerm) {
if (searchTerm == null || searchTerm.trim().isEmpty()) {
return Collections.emptyList();
}
// Perform database search
return userRepository.findByNameContaining(searchTerm);
}
}
Advanced Validation Techniques
Comprehensive Validation Method
public static boolean isValidString(String input) {
return input != null &&
!input.trim().isEmpty() &&
input.trim().length() > 0;
}
- Prefer
.trim().isEmpty()
for user inputs
- Use
Objects.requireNonNull()
for critical validations
- Implement early return strategies
- Avoid multiple string methods in tight loops
By applying these practical examples, developers can create robust string validation mechanisms in their Java applications, ensuring data integrity and preventing potential runtime errors.