15 Java String Method Questions I Practiced — Here's What I Actually Learned
I've been learning Java for a while now, and strings are everywhere. But knowing that String exists and actually knowing how to use it in real situations are two very different things.
Here's everything I picked up, question by question.
Q1 — Why Does Login Fail Even When the Password is Correct?
Scenario: User types Admin123 (with a trailing space). Login fails even though the password matches.
This one is so common in real applications and nobody talks about it enough. The fix is .trim() — it removes all leading and trailing whitespace from a string before you compare it.
if (password.equals(CheckPassword.trim())) {
System.out.println("Login Success");
}
What I learned: Never compare user input directly. Always .trim() first. Users accidentally add spaces all the time — especially on mobile keyboards.
Q2 — UI Sends "Vijay" but Database Has "vijay" — How to Compare Safely?
Scenario: The UI sends the name with a capital V but your database stores it lowercase.
.equals() is case-sensitive — "Vijay" and "vijay" would fail. The fix is .equalsIgnoreCase() which ignores the case completely.
if (DataBaseName.equalsIgnoreCase(UIName.trim()))
System.out.println("login success");
What I learned: Always use .equalsIgnoreCase() for usernames and names. Use .equals() only when case matters — like passwords.
Q3 — What's the Difference Between == and .equals()?
This question genuinely confused me before I practiced it.
String s1 = "JAVA";
String s2 = new String("JAVA");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
-
==compares memory addresses (reference).s1is in the String Pool,s2is a new object in the heap — different address, sofalse. -
.equals()compares the actual value — both contain "JAVA", sotrue.
What I learned: Never use == to compare strings in Java. Always use .equals(). The == trap has broken countless real applications.
Q4 — Validate an Email Address
Scenario: Keep asking the user for an email until it contains @ and .
if (CheckEmail.contains("@") && CheckEmail.contains(".")) {
System.out.println("Your Email : " + CheckEmail);
condition = false;
}
.contains() checks if a string has a specific sequence of characters inside it. I put it inside a while loop to keep asking until the input is valid.
What I learned: .contains() is great for quick format checks. For production-level validation you'd use regex, but .contains() is perfect for learning the logic first.
Q5 — Convert a String to an Integer
Scenario: User types "1234" as text. You need it as a number to do math.
int number = Integer.parseInt(scan.nextLine());
Integer.parseInt() converts a numeric string into an actual int. If the user types letters instead of numbers, it throws a NumberFormatException — which is why real apps wrap this in try-catch.
What I learned: Keyboard input is always a String. Whenever you need a number from the user, Integer.parseInt() is your go-to.
Q6 — Remove Extra Spaces from Start and End
String extraSpace = " welcome to java ";
System.out.println(extraSpace.trim()); // "welcome to java"
.trim() again — but this time I saw it as a standalone method, not just inside a comparison. It's great for cleaning up any user-facing text before displaying or storing it.
Q7 — Count How Many Times a Word Appears
Scenario: "Java is easy, Java is powerful" — how many times does "Java" appear?
This one I still had a doubt on during practice. The clean way to count occurrences:
String count = "java is easy , java is powerful";
int occurrences = count.split("java", -1).length - 1;
System.out.println(occurrences); // 2
Split the string by the word you're looking for. The number of pieces minus 1 = the number of occurrences. The -1 flag makes sure empty trailing strings are counted too.
What I learned: There's no .countOccurrences() method in Java — you build it using .split() or a loop.
Q8 — Reverse a String Without StringBuilder
Scenario: Reverse "abishek" without using StringBuilder.reverse().
String word = "abishek";
String reverse = "";
for (int i = 0; i < word.length(); i++) {
reverse = word.charAt(i) + reverse;
}
System.out.println(reverse); // kehsiba
.charAt(i) picks out one character at a time by its index. Each character is added to the front of the result string, which builds the reverse naturally.
What I learned: .charAt() is how you access individual characters in a string. This loop pattern is a classic interview question — worth memorizing.
Q9 — Check if a String is a Palindrome
A palindrome reads the same forwards and backwards — like "madam" or "racecar".
String reverse = "";
for (int i = 0; i < word.length(); i++) {
reverse = word.charAt(i) + reverse;
}
System.out.println(reverse.equals(word) ? "it is palindrome" : "not palindrome");
Reverse the string using the same loop as Q8, then compare it to the original with .equals(). I also used the ternary operator here which keeps the code clean.
What I learned: Palindrome check = reverse + compare. That's it.
Q10 — Remove Duplicate Characters
Scenario: Input "aabbccddee" → Output "abcde"
String duplicate = "aabbccddee";
String result = "";
for (int i = 0; i < duplicate.length(); i++) {
if (result.indexOf(duplicate.charAt(i)) == -1) {
result += duplicate.charAt(i);
}
}
System.out.println(result); // abcde
.indexOf() returns the position of a character in a string — or -1 if it's not there. I use that -1 check to decide if the character has already been added to the result.
What I learned: .indexOf() returning -1 means "not found" — this is a very useful pattern for checking membership in a string.
Q11 — Extract Part of a String (Log Parser)
Scenario: Log entry is "ERROR: File not found". You only want "File not found".
String logFormat = "ERROR: File not found";
System.out.println(logFormat.substring(7)); // File not found
.substring(7) starts from index 7 and returns everything after it. You can also do .substring(start, end) to get a specific range.
What I learned: .substring() is essential for parsing structured text like logs, file paths, or formatted data where you know the position of what you need.
Q12 — Parse a CSV String
Scenario: "Abishek,Chennai,23" — extract name, city, age separately.
String CSV = "Abishek,Chennai,23";
String[] result = CSV.split(",");
System.out.println("Name: " + result[0]);
System.out.println("City: " + result[1]);
System.out.println("Age: " + result[2]);
.split(",") breaks the string wherever it finds a comma and returns an array of pieces. I then access each piece by its array index.
What I learned: .split() is how you parse any delimiter-separated data — CSV files, API responses, config strings, all of it.
Q13 — Replace Words in a String
Scenario: Replace "Java" with "Spring Boot" and "Love" with "Hate" in one sentence.
String given = "I Love Java Programming";
String result = given.replace("Java", "C++").replace("Love", "Hate");
System.out.println(result); // I Hate C++ Programming
.replace() swaps every occurrence of a word with something new. You can chain multiple .replace() calls together since each one returns a new String.
What I learned: String methods in Java return new strings — they don't modify the original. This is because strings in Java are immutable. You have to store the result.
Q14 — Validate a Mobile Number
Scenario: Validate that a number is 10 digits and starts with 6, 7, 8, or 9.
if (number.matches("[6-9][0-9]{9}")) {
System.out.println("Valid number");
}
.matches() checks if the entire string matches a regular expression (regex) pattern. [6-9] means any digit from 6 to 9. [0-9]{9} means exactly 9 more digits after that. Together = a valid Indian mobile number format.
What I learned: .matches() with regex is the professional way to validate formats — phone numbers, emails, passwords, PINs. This was my first time really using regex and it clicked here.
Q15 — Split a String by a Custom Delimiter
Scenario: "apple#banana#mango" — split by # and store in an array.
String GivenString = "apple#banana#mango";
String[] arr = GivenString.split("#");
System.out.println(Arrays.toString(arr)); // [apple, banana, mango]
Same concept as Q12 but with a custom delimiter. Arrays.toString() prints the array in a readable format instead of the raw memory address.
What I learned: .split() works with any delimiter — comma, hash, pipe, space. And always use Arrays.toString() when printing arrays or you'll get gibberish output.
The Full Method Cheat Sheet
Here's every method I used across all 15 questions:
| Method | What It Does |
|---|---|
.trim() |
Removes whitespace from start and end |
.equals() |
Compares values — case sensitive |
.equalsIgnoreCase() |
Compares values — ignores case |
.contains() |
Checks if a substring exists inside |
.charAt(i) |
Gets the character at a specific index |
.length() |
Returns total number of characters |
.indexOf() |
Finds position of a character (-1 if not found) |
.substring(n) |
Returns string from index n onwards |
.substring(a, b) |
Returns string from index a to b |
.split(delimiter) |
Breaks string into array by a separator |
.replace(old, new) |
Swaps all occurrences of a word |
.matches(regex) |
Checks if string matches a pattern |
Integer.parseInt() |
Converts numeric string to int |
What I Actually Took Away From This
The biggest thing these 15 questions taught me is that String methods are not just syntax — they're tools for solving real problems.
Before this, I knew .trim() existed. Now I know when I need it — every time I take user input. I knew .split() was a thing. Now I know it's how you parse CSV data. I knew == and .equals() were different. Now I know exactly why — and why getting it wrong breaks login systems.
If you're learning Java, I'd genuinely recommend doing scenario-based practice over reading method documentation. The methods stick when you see the problem they solve.
Top comments (0)