In this blog, we will explore 15 practical Java string scenarios using simple and reusable methods. Think of this as your string survival guide for interviews and real-world coding.
1.Fixing Login Failures Due to Extra Spaces
A common issue occurs when users accidentally include extra spaces while entering credentials. For example, a password like "Admin123 " may cause authentication failure.
Solution: Use trim()
input.trim().equals(actual);
This removes unwanted spaces from the beginning and end of the string.
2.Case-Insensitive Username Comparison
Users may enter usernames in different cases, such as "Vijay" instead of "vijay".
Solution: Use equalsIgnoreCase()
a.equalsIgnoreCase(b);
This ensures that case differences do not affect the comparison.
3.Understanding == vs equals()
String s1 = "Java";
String s2 = new String("Java");
== compares memory locations
equals() compares actual string values
Always use equals() when comparing string content.
4.Basic Email Validation
email.contains("@") && email.contains(".");
This is a simple way to check whether an email has basic structural elements.
5.Converting String to Integer
int n = Integer.parseInt("1234");
This is useful when working with numeric input received as a string.
6.Removing Extra Spaces
str.trim();
This removes spaces only from the start and end of the string, not in between words.
7.Counting Word Occurrences
String[] words = str.split(" ");
You can loop through the array and count occurrences of a specific word such as "Java".
8.Reversing a String
for(int i = str.length() - 1; i >= 0; i--)
This approach builds a reversed string by iterating from the end to the beginning.
9.Checking for Palindrome
str.equals(reverse(str));
A palindrome is a string that reads the same forwards and backwards, such as "madam".
10.Removing Duplicate Characters
if(result.indexOf(ch) == -1)
This ensures only unique characters are added to the result string.
11.Extracting Log Messages
log.substring(log.indexOf(":") + 2);
This extracts meaningful information like "File not found" from a log string.
12.Splitting CSV Data
String[] arr = data.split(",");
This is commonly used to parse comma-separated values such as "Vijay,25,Chennai".
13.Replacing Words
str.replace("Java", "Spring Boot");
This allows dynamic modification of string content.
14.Validating Mobile Numbers
num.matches("\\d{10}");
This checks if the string contains exactly 10 digits.
15.splitting Custom Data
str.split("#");
Useful when working with custom delimiters like "apple#banana#mango".
Strings in Java are immutable. This means that once a string is created, it cannot be changed. Any modification results in a new string being created.
By understanding and applying these methods, you can handle input validation, data transformation, and text processing with confidence.
Top comments (0)