Practical Usage Examples
public class InputValidator {
public static boolean isValidPassword(String password) {
return password.length() >= 8 && password.length() <= 20;
}
public static void main(String[] args) {
String userPassword = "LabEx2023";
System.out.println("Password Valid: " + isValidPassword(userPassword));
}
}
Text Truncation
public class TextTruncator {
public static String truncateText(String text, int maxLength) {
return text.length() > maxLength
? text.substring(0, maxLength) + "..."
: text;
}
public static void main(String[] args) {
String longText = "Java Programming in LabEx Learning Platform";
System.out.println(truncateText(longText, 20));
}
}
String Comparison
public class StringComparison {
public static void compareStrings(String str1, String str2) {
System.out.println("First String Length: " + str1.length());
System.out.println("Second String Length: " + str2.length());
System.out.println("Strings Equal Length: " + (str1.length() == str2.length()));
}
public static void main(String[] args) {
compareStrings("Hello", "World");
}
}
Usage Scenarios
Scenario |
Length Check Purpose |
Password Validation |
Ensure minimum/maximum length |
Text Display |
Truncate long descriptions |
Data Processing |
Compare string sizes |
User Input Verification |
Validate input constraints |
Length Calculation Flow
graph TD
A[String Length Calculation] --> B{Validation Purpose}
B --> |Security| C[Password Length Check]
B --> |Display| D[Text Truncation]
B --> |Comparison| E[String Size Comparison]
C --> F[Accept/Reject]
D --> G[Shortened Text]
E --> H[Equality Determination]
Best Practices
- Use
.length()
for most scenarios
- Implement clear validation logic
- Consider performance in large-scale applications
- Handle edge cases systematically
These practical examples demonstrate how string length calculations are crucial in various Java programming contexts.