DEV Community

Cover image for Java Scenario Questions(string)
Ajay Raja
Ajay Raja

Posted on

Java Scenario Questions(string)

1.Handling Trailing Spaces in Password:

Used: trim() + equals()
User input may contain unwanted spaces. By using trim(), spaces at the beginning and end are removed before comparing the password.

input.trim().equals(correctPassword);
Enter fullscreen mode Exit fullscreen mode

2.Case-Insensitive Comparison:

Used: equalsIgnoreCase()
This method allows comparison of two strings without considering uppercase and lowercase differences.

nameFromUI.equalsIgnoreCase(nameFromDB);
Enter fullscreen mode Exit fullscreen mode

3.Difference Between == and equals():

Used: equals()
In Java, == compares memory references, while equals() compares actual string values.
For string comparison, always use equals().

4.Email Validation:

Used:contains()
To perform basic validation, check whether the email contains '@' and '.'.

email.contains("@") && email.contains(".");
Enter fullscreen mode Exit fullscreen mode

5.String to Integer Conversion:

Used:Integer.parseInt()
This method converts a string into an integer so that arithmetic operations can be performed.

int number = Integer.parseInt(str);
Enter fullscreen mode Exit fullscreen mode

6.Removing Extra Spaces:

Used:trim()
Removes unnecessary spaces from the beginning and end of a string.

str.trim();
Enter fullscreen mode Exit fullscreen mode

7.Count Occurrences of a Word (To Be Discussed):

Used:indexOf()
The method is used to find the position of a substring. By repeatedly searching and moving forward, occurrences can be counted.

8.Reverse a String:

Used:charAt()
Characters are accessed from the end of the string and appended to form the reversed string.

for (int i = str.length() - 1; i >= 0; i--)
Enter fullscreen mode Exit fullscreen mode

9.Palindrome Check:

Used:charAt() + equals()
The string is reversed and compared with the original. If both are equal, it is a palindrome.

10.Remove Duplicate Characters:

Used:indexOf()
Each character is checked before adding to the result. If it already exists, it is skipped.

if (result.indexOf(ch) == -1)
Enter fullscreen mode Exit fullscreen mode

11.Extract Substring from Log:

Used:substring() + indexOf()
The position of : is found, and the text after it is extracted.

12.Split CSV Data (To Be Discussed):

Used:split()
The string is divided into parts using a comma delimiter and stored in an array.

13.Replace Substring:

Used:replace()
Replaces one part of the string with another.

str.replace("Java", "Spring Boot");
Enter fullscreen mode Exit fullscreen mode

14.Mobile Number Validation:[TBD]

Used:matches()
Regex is used to ensure the number contains exactly 10 digits.

str.matches("\\d{10}");
Enter fullscreen mode Exit fullscreen mode

15.Split String Using Delimiter:

Used:split()
Splits the string into parts using a specific delimiter like #.

Top comments (0)