Strings are an integral part of any programming language and are widely used in various applications. In Java, strings are objects and have their own methods and properties. In this blog post, we will be discussing the top 30 frequently asked Java interview programs on strings. These programs cover a wide range of topics, from basic string manipulation to advanced string algorithms.
We will start with basic programs such as finding the length of a string, concatenating strings, and comparing strings. We will then move on to more advanced programs such as finding the first non-repeated character in a string, finding all the substrings of a given string, and finding all the possible combinations of a given string.
We will also cover programs that deal with string manipulation such as converting a string to uppercase or lowercase, checking if a given string starts or ends with a specific substring, and finding the position of a specific word in a given string.
We will also discuss the use of the string split method, which is a powerful tool for parsing strings. We will cover programs that deal with finding the most frequent character in a given string, finding the second most frequent character in a given string, and finding the first and last occurrence of a specific character in a given string.
In addition to these programs, we will also cover programs that deal with finding the common elements in two given strings, finding the number of words in a given string and finding the index of the first non-repeated character in a given string.
Overall, this blog post is designed to provide a comprehensive guide to the top 30 frequently asked Java interview programs on strings. Whether you are a beginner or an experienced Java developer, these programs will help you to improve your skills and prepare for your next Java interview.
Contents
- 1 Top 30 Java Interview Programs on Strings:
- 1.1 Question 1: How can you reverse a string in Java?
- 1.2 Question 2: How can you count the number of vowels in a given string in Java?
- 1.3 Question 3: How can you find the first non-repeated character in a given string in Java?
- 1.4 Question 4: How can you check if a given string is a palindrome?
- 1.5 Question 5: How can you count the number of words in a given string in Java?
- 1.6 Question 6: How can you remove all whitespace from a given string in Java?
- 1.7 Question 7: How can you find the longest and shortest word in a given string in Java?
- 1.8 Question 8: How can you remove all duplicate characters from a given string in Java?
- 1.9 Question 9: How can you check if two given strings are anagrams in Java?
- 1.10 Question 10: How can you check if a given string contains only digits in Java?
- 1.11 Question 11: How can you count the number of occurrences of a given substring in a string in Java?
- 1.12 Question 12: How can you find the common prefix of two given strings in Java?
- 1.13 Question 13: How can you find the common suffix of two given strings in Java?
- 1.14 Question 14: How can you remove a specific character from a given string in Java?
- 1.15 Question 15: How can you reverse a given string without using any inbuilt functions in Java?
- 1.16 Question 16: How can you find the first non-repeated character in a given string in Java?
- 1.17 Question 17: How can you find the frequency of each word in a given string in Java?
- 1.18 Question 18: How to find all the permutations of the string?
- 1.19 Question 19: How can you convert a given string to uppercase or lowercase in Java?
- 1.20 Question 20: How can you check if a given string starts or ends with a specific substring in Java?
- 1.21 Question 21: How can you find the most frequent character in a given string in Java?
- 1.22 Question 22: How can you find the second most frequent character in a given string in Java?
- 1.23 Question 23: How can you find the position of a specific word in a given string in Java?
- 1.24 Question 24: How can you use the split() method to split a given string into an array of substrings in Java?
- 1.25 Question 25: How can you find the first and last occurrence of a specific character in a given string in Java?
- 1.26 Question 26: How can you find the common elements in two given strings in Java?
- 1.27 Question 27: How can you find the number of words in a given string in Java?
- 1.28 Question 28: How can you find the index of the first non-repeated character in a given string in Java?
- 1.29 Question 29: How can you find all the substrings of a given string in Java?
- 1.30 Question 30: How can you use the replace() method to replace a specific substring in a given string in Java?
- 2 Follow us on YouTube for more Interview Program Questions on Java:
- 3 See you Soon!
Top 30 Java Interview Programs on Strings:
Question 1: How can you reverse a string in Java?
public static void main(String[] args) {
String str = "Hello World";
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse().toString());
}
Output: “dlroW olleH”
Explanation: The StringBuilder class has a reverse() method that can be used to reverse the characters in a string. We create a StringBuilder object with the input string, then call the reverse() method on it and finally convert it back to a string using toString() method.
Apart from this, there are different ways we can reverse the string in Java which can be asked in interview. We recommend to take look on 11 ways to reverse the string in Java.

Question 2: How can you count the number of vowels in a given string in Java?
public static void main(String[] args) {
String str = "java is a popular language";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
System.out.println("Number of vowels: " + count);
}
Output: “Number of vowels: 11”
Explanation: The program uses a for loop to iterate through each character in the string. Inside the loop, an if statement checks if the current character is a vowel. If it is, the count variable is incremented. Finally, the number of vowels is printed to the console.

Question 3: How can you find the first non-repeated character in a given string in Java?
public static void main(String[] args) {
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
boolean unique = true;
for (int j = 0; j < str.length(); j++) {
if (i != j && str.charAt(i) == str.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
System.out.println("The first non-repeated character is: " + str.charAt(i));
break;
}
}
}
Output: “The first non-repeated character is: H”
Explanation: The program uses nested for loops. The outer loop iterates through each character in the string, and the inner loop compares the current character to every other character in the string. If the current character is not equal to the inner loop character and is unique, the program prints the character and breaks the loop.

Question 4: How can you check if a given string is a palindrome?
public static void main(String[] args) {
String str = "madam";
StringBuilder sb = new StringBuilder(str);
String reversed = sb.reverse().toString();
if (str.equals(reversed)) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");
}
}
Output: “madam is a palindrome”
Explanation: The program creates a StringBuilder object with the input string and reverses it. Then it compares the original string with the reversed string. If they are equal, the string is a palindrome, if not, it is not a palindrome.

Question 5: How can you count the number of words in a given string in Java?
public static void main(String[] args) {
String str = "Hello World, How are you?";
String[] words = str.split(" ");
System.out.println("Number of words: " + words.length);
}
Output: “Number of words: 5”
Explanation: The program uses the split() method to split the string into an array of words based on the space character. Then it uses the length property of the array to get the number of words in the string.

Question 6: How can you remove all whitespace from a given string in Java?
public static void main(String[] args) {
String str = " Hello World ";
String newString = str.replaceAll("\\s", "");
System.out.println(newString);
}
Output: “HelloWorld”
Explanation: The program uses the replaceAll() method, which takes a regular expression as its first argument. The regular expression “\s” matches any whitespace character. The second argument is the string to replace the matched characters with, in this case, an empty string.

Question 7: How can you find the longest and shortest word in a given string in Java?
public static void main(String[] args) {
String str = "Hello World, How are you?";
String[] words = str.split(" ");
String longest = "", shortest = words[0];
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
if (word.length() < shortest.length()) {
shortest = word;
}
}
System.out.println("Longest word: " + longest);
System.out.println("Shortest word: " + shortest);
}
Output: “Longest word: World,” “Shortest word: How”
Explanation: The program uses the split() method to split the string into an array of words based on the space character. Then it uses two variables, longest and shortest, to store the longest and shortest word respectively. A for-each loop iterates through each word in the array, using an if statement to compare the length of the current word to the length of the longest and shortest words. If the current word is longer than the current longest word, it becomes the new longest word. Similarly, if the current word is shorter than the current shortest word, it becomes the new shortest word. Finally, the longest and shortest words are printed to the console.

Question 8: How can you remove all duplicate characters from a given string in Java?
public static void main(String[] args) {
String str = "Hello World";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (sb.indexOf(String.valueOf(str.charAt(i))) == -1) {
sb.append(str.charAt(i));
}
}
System.out.println(sb.toString());
}
Output: “Helo Wrd”
Explanation: The program creates a StringBuilder object to store the characters of the string without duplicates. A for loop iterates through each character in the string. The indexOf() method is used to check if the current character is already present in the StringBuilder object. If it is not present, the character is appended to the StringBuilder object. Finally, the toString() method is called to convert the StringBuilder object back to a string.

Question 9: How can you check if two given strings are anagrams in Java?
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
int[] arr1 = new int[26];
int[] arr2 = new int[26];
for (int i = 0; i < str1.length(); i++) {
arr1[str1.charAt(i) - 'a']++;
}
for (int i = 0; i < str2.length(); i++) {
arr2[str2.charAt(
i) - 'a']++;
}
boolean isAnagram = true;
for (int i = 0; i < 26; i++) {
if (arr1[i] != arr2[i]) {
isAnagram = false;
break;
}
}
if (isAnagram) {
System.out.println(str1 + " and " + str2 + " are anagrams");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
Output: “listen and silent are anagrams”
Explanation: The program uses two integer arrays, arr1 and arr2, to store the frequency of each character in the two input strings. Two for loops iterate through each character in the strings, incrementing the corresponding element in the arrays. Then, a for loop iterates through each element in the arrays, comparing the frequency of each character in the two strings. If all the elements in the arrays are equal, the two strings are anagrams, otherwise, they are not anagrams.

Question 10: How can you check if a given string contains only digits in Java?
public static void main(String[] args) {
String str = "1234567890";
boolean isDigits = true;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
isDigits = false;
break;
}
}
if (isDigits) {
System.out.println(str + " contains only digits");
} else {
System.out.println(str + " contains non-digit characters");
}
}
Output: “1234567890 contains only digits”
Explanation: The program uses a for loop to iterate through each character in the string. Inside the loop, the isDigit() method of the Character class is used to check if the current character is a digit. If it is not, the variable isDigits is set to false, and the loop breaks. Finally, the program prints a message indicating whether the string contains only digits or not.

Question 11: How can you count the number of occurrences of a given substring in a string in Java?
public static void main(String[] args) {
String str = "Hello World, How are you?";
String sub = "o";
int count = 0;
int index = 0;
while ((index = str.indexOf(sub, index)) != -1) {
count++;
index += sub.length();
}
System.out.println("Number of occurrences of " + sub + ": " + count);
}
Output: “Number of occurrences of o: 4”
Explanation: The program uses the indexOf() method to find the index of the substring in the string. It starts searching for the substring at index 0, and stores the index in the variable ‘index’. If the substring is found, the index is added to the count, and the search is continued starting from the next index by adding the length of the substring to the current index. If the substring is not found, the indexOf() method returns -1, and the loop breaks. Finally, the program prints the number of occurrences of the substring in the string.

Question 12: How can you find the common prefix of two given strings in Java?
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Heard";
StringBuilder sb = new StringBuilder();
int minLen = Math.min(str1.length(), str2.length());
for (int i = 0; i < minLen; i++) {
if (str1.charAt(i) == str2.charAt(i)) {
sb.append(str1.charAt(i));
} else {
break;
}
}
System.out.println("Common prefix: " + sb.toString());
}
Output: “Common prefix: He”
Explanation: The program first finds the minimum length of the two input strings using the Math.min method. It then uses a for loop to iterate through each character of the two strings up to the minimum length. If the current character in both strings is the same, it is added to the StringBuilder object ‘sb’. If the characters are different, the loop breaks and the common prefix is stored in the StringBuilder object. Finally, the program prints the common prefix using the toString() method of the StringBuilder object.

Question 13: How can you find the common suffix of two given strings in Java?
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Guava";
StringBuilder sb = new StringBuilder();
int minLen = Math.min(str1.length(), str2.length());
for (int i = 1; i <= minLen; i++) {
if (str1.charAt(str1.length() - i) == str2.charAt(str2.length() - i)) {
sb.append(str1.charAt(str1.length() - i));
} else {
break;
}
}
System.out.println("Common suffix: " + sb.reverse().toString());
}
Output: “Common suffix: ava”
Explanation: The program first finds the minimum length of the two input strings using the Math.min method. It then uses a for loop to iterate through each character of the two strings in reverse order up to the minimum length. If the current character in both strings is the same, it is added to the StringBuilder object ‘sb’. If the characters are different, the loop breaks and the common suffix is stored in the StringBuilder object. Finally, the program prints the common suffix by reversing the string using the reverse method of the StringBuilder class and using the toString() method to convert the StringBuilder object back to a string.

Question 14: How can you remove a specific character from a given string in Java?
public static void main(String[] args) {
String str = "Hello World";
char remove = 'l';
str = str.replaceAll(Character.toString(remove), "");
System.out.println(str);
}
Output: “Heo Word”
Explanation: The program first defines the string and the character to be removed. It then uses the replaceAll() method, which takes two arguments: a regular expression and a replacement string. The regular expression is the character to be removed, which is passed in as a string using the toString() method of the Character class. The replacement string is an empty string. This will replace all occurrences of the character with an empty string, effectively removing it from the original string. Finally, the program prints the modified string.

Question 15: How can you reverse a given string without using any inbuilt functions in Java?
public static void main(String[] args) {
String str = "Hello";
char[] arr = str.toCharArray();
for(int i=0; i<arr.length/2; i++) {
char temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
str = new String(arr);
System.out.println("Reversed String : " + str);
}
Output : “olleH”
Explanation: In this program, first, the given string is converted to a character array. Then it uses a for loop to iterate over half of the array, swapping the elements at the start and end of the array, working inwards. Finally, the reversed character array is converted back to a string and printed.

Question 16: How can you find the first non-repeated character in a given string in Java?
public static void main(String[] args) {
String str = "teeter";
int[] charCount = new int[256];
for (int i = 0; i < str.length(); i++) {
charCount[str.charAt(i)]++;
}
int index = -1, i;
for (i = 0; i < str.length(); i++) {
if (charCount[str.charAt(i)] == 1) {
index = i;
break;
}
}
System.out.println("The first non-repeated character in " + str + " is " + str.charAt(index));
}
Output: “The first non-repeated character in teeter is r”
Explanation: The program uses an array of integers to store the count of each character in the string. A for loop iterates through the string and increments the corresponding element in the array for each character. Then, another for loop iterates through the string again, and checks if the count of the current character is 1. If it is, the index of that character is stored in the variable ‘index’ and the loop breaks. Finally, the program prints the first non-repeated character using the index variable.

Question 17: How can you find the frequency of each word in a given string in Java?
public static void main(String[] args) {
String str = "I am learning Java, it is interesting and challenging";
String[] words = str.split(" ");
HashMap<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
Output: “I : 1” “am : 1” “learning : 1” “Java, : 1” “it : 1” “is : 2” “interesting : 1” “and : 1” “challenging : 1”
Explanation: The program uses the split() method to split the string into an array of words. It then uses a HashMap to store the frequency of each word. A for-each loop iterates through each word in the array, checking if the word is already present in the HashMap. If it is, the frequency count is incremented by 1. If it is not, a new entry is added to the HashMap with a frequency count of 1. Finally, another for-each loop iterates through the HashMap, printing the frequency of each word.

Question 18: How to find all the permutations of the string?
public class Permute {
public static void permute(String str, int l, int r) {
if (l == r)
System.out.println(str);
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
public static void main(String[] args) {
String str = "abc";
int n = str.length();
permute(str, 0, n - 1);
}
}
Output : “abc”,”acb”,”bac”,”bca”,”cab”,”cba”
Explanation: The program uses a recursive function permute() which takes 3 arguments, a string, and 2 integers l and r. The permute function generates all permutations of the characters of the string. In the function, if the left index is equal to the right index, it prints the string. Else, it swaps the leftmost character with all other characters one by one and then recursively calls the permute function with the left+1, right. The main method calls the permute function with the given string, left index 0 and right index length-1. The permute method calls the swap method for swapping the characters of the string.

Question 19: How can you convert a given string to uppercase or lowercase in Java?
public class ConvertCase {
public static void main(String[] args) {
String originalString = "Convert Me to UpperCase";
String upperCaseString = originalString.toUpperCase();
String lowerCaseString = originalString.toLowerCase();
System.out.println("Original String: " + originalString);
System.out.println("Uppercase String: " + upperCaseString);
System.out.println("Lowercase String: " + lowerCaseString);
}
}
Output:
Original String: Convert Me to UpperCase
Uppercase String: CONVERT ME TO UPPERCASE
Lowercase String: convert me to uppercase
Explanation: In this program, the toUpperCase()
and toLowerCase()
methods are used to convert the original string to uppercase and lowercase respectively. These methods are a part of the String
class in Java and do not take any arguments. The toUpperCase()
method returns a new string in which all characters have been converted to uppercase, and the toLowerCase()
method returns a new string in which all characters have been converted to lowercase. The program then prints the original string, the uppercase string, and the lowercase string.
In addition to these methods, Java also provides the Character.toUpperCase()
and Character.toLowerCase()
methods which can be used to convert a single character to uppercase or lowercase respectively.
It is important to note that when you use these methods, it creates a new string with the modification, it does not change the original string.

Question 20: How can you check if a given string starts or ends with a specific substring in Java?
public class StartsWithEndsWith {
public static void main(String[] args) {
String str = "Hello World";
String prefix = "Hello";
String suffix = "World";
System.out.println("String starts with '" + prefix + "': " + str.startsWith(prefix));
System.out.println("String ends with '" + suffix + "': " + str.endsWith(suffix));
}
}
Output:
String starts with ‘Hello’: true
String ends with ‘World’: true
Explanation: In this program, the startsWith()
and endsWith()
methods are used to check if the given string starts or ends with a specific substring respectively. These methods are a part of the String
class in Java and take a single argument, which is the substring to check for. The startsWith()
method returns true
if the original string starts with the specified substring and false
otherwise. Similarly, the endsWith()
method returns true
if the original string ends with the specified substring and false
otherwise. In this example, both the methods return true as the original string starts with the substring “Hello” and ends with the substring “World”.
It’s important to note that these methods are case-sensitive, so if you want to check for a substring regardless of case, you can convert the original string and the substring to lowercase or uppercase using the toLowerCase()
or toUpperCase()
methods before calling the startsWith()
or endsWith()
methods.

Question 21: How can you find the most frequent character in a given string in Java?
public class MostFrequentCharacter {
public static void main(String[] args) {
String str = "abracadabra";
int[] count = new int[256];
int max = -1;
char result = ' ';
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
System.out.println("Most frequent character is '" + result + "' with count: " + max);
}
}
Output: Most frequent character is ‘a’ with count: 5
Explanation: In this program, an integer array count[] is used to store the count of each character in the given string. The count of each character is incremented using the charAt()
method which returns the character at the specified index of the string.
A variable max
is initialized to -1, which will keep track of the maximum count of any character. A variable result
is initialized as space, which will keep track of the most frequent character. Then, a for loop is used to traverse through the string.
And inside the loop, the count of the current character is incremented and if the current count is greater than the max count, the max count and the result character are updated. Finally, the program prints the most frequent character and its count.
It is important to note that this approach uses an array to store the count of characters, so it has a time complexity of O(n) where n is the number of characters in the string. And also it assumes that the input string only contains ASCII characters.

Question 22: How can you find the second most frequent character in a given string in Java?
public class SecondMostFrequent {
public static void main(String[] args) {
String str = "abracadabra";
int[] count = new int[256];
int maxCount = -1;
char maxChar = ' ';
int secondMaxCount = -1;
char secondMaxChar = ' ';
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > maxCount) {
secondMaxCount = maxCount;
secondMaxChar = maxChar;
maxCount = count[i];
maxChar = (char) i;
} else if (count[i] > secondMaxCount && count[i] != maxCount) {
secondMaxCount = count[i];
secondMaxChar = (char) i;
}
}
System.out.println("Second most frequent character is '" + secondMaxChar + "' with count: " + secondMaxCount);
}
}
Output: Second most frequent character is ‘r’ with count: 2
Explanation: In this program, an integer array count[] is used to store the count of each character in the given string. The count of each character is incremented using the charAt()
method which returns the character at the specified index of the string. Two variables maxCount
and maxChar
are initialized to -1 and ‘ ‘, which will keep track of the maximum count and character of any character respectively.
Two variables secondMaxCount
and secondMaxChar
are initialized to -1 and ‘ ‘, which will keep track of the second maximum count and character of any character respectively.
Then, a for loop is used to traverse through the string and another for loop is used to traverse through the count array.
In the first for loop, the count of the current character is incremented.
In the second for loop, if the count of the current character is greater than the maxCount, the secondMaxCount and the secondMaxChar are updated with the maxCount and maxChar, and maxCount and maxChar are updated with the count and the current character. Else if the count of the current character is greater than the secondMaxCount and is not equal to maxCount, the secondMaxCount and the secondMaxChar are updated with the count and the current character.

Question 23: How can you find the position of a specific word in a given string in Java?
public class PositionOfWord {
public static void main(String[] args) {
String str = "This is a sample sentence for demonstration";
String word = "sentence";
int position = str.indexOf(word);
if (position != -1) {
System.out.println("The word '" + word + "' was found at position: " + position);
} else {
System.out.println("The word '" + word + "' was not found in the string.");
}
}
}
Output: The word ‘sentence’ was found at position: 17
Explanation: In this program, the indexOf(String str)
method is used to find the position of a specific word in a given string. This method is a part of the String
class in Java and takes a single argument, which is the substring to search for. The indexOf()
method returns the index within the original string of the first occurrence of the specified substring, or -1 if the substring is not present in the string. In this example, the word “sentence” is found at position 17.
It’s important to note that this method is case-sensitive, so if you want to find the position of a word regardless of case, you can convert the original string and the word to lowercase or uppercase using the toLowerCase()
or toUpperCase()
methods before calling the indexOf()
method.
Also, you can use lastIndexOf(String str)
method to find the position of last occurrence of the specific word.

Question 24: How can you use the split()
method to split a given string into an array of substrings in Java?
public class SplitString {
public static void main(String[] args) {
String str = "Hello, World! How are you?";
String[] words = str.split("\\s+"); // using regular expression for whitespace as delimiter
for (String word : words) {
System.out.println(word);
}
}
}
Output:
Hello,
World!
How
are
you?
Explanation: In this program, the split()
method is used to split the given string into an array of substrings based on the specified delimiter. This method is a part of the String
class in Java and takes a single argument, which is the regular expression (regex) to use as the delimiter. In this example, the delimiter is "\\s+"
, which represents one or more whitespace characters. The resulting array of substrings is then assigned to the words
variable and printed out using a for-each loop.
Also, you can use the split(CharSequence delimiter, int limit)
method which allows you to limit the number of splits. In this method, delimiter
is the delimiter to use and limit
is the maximum number of substrings to return.

Question 25: How can you find the first and last occurrence of a specific character in a given string in Java?
public class FirstLastOccurrence {
public static void main(String[] args) {
String str = "Hello World";
char target = 'l';
int first = str.indexOf(target);
int last = str.lastIndexOf(target);
if (first != -1) {
System.out.println("The first occurrence of '" + target + "' is at index: " + first);
} else {
System.out.println("The character '" + target + "' was not found in the string.");
}
if (last != -1) {
System.out.println("The last occurrence of '" + target + "' is at index: " + last);
} else {
System.out.println("The character '" + target + "' was not found in the string.");
}
}
}
Output:
The first occurrence of ‘l’ is at index: 2
The last occurrence of ‘l’ is at index: 9
Explanation: In this program, the indexOf(int ch)
and lastIndexOf(int ch)
methods are used to find the first and last occurrence of a specific character in a given string respectively. These methods are a part of the String
class in Java and take a single argument, which is the character to search for.
The indexOf()
method returns the index within the original string of the first occurrence of the specified character, or -1 if the character is not present in the string. The lastIndexOf()
method returns the index within the original string of the last occurrence of the specified character, or -1 if the character is not present in the string. In this example, the first occurrence of ‘l’ is at index 2 and the last occurrence of ‘l’ is at index 9.
It’s important to note that these methods are case-sensitive, so if you want to find the first and last occurrence of a character regardless of case, you can convert the original string to lowercase or uppercase using the toLowerCase()
or toUpperCase()
methods before calling the indexOf()
or lastIndexOf()
methods.

Question 26: How can you find the common elements in two given strings in Java?
public class CommonElements {
public static void main(String[] args) {
String str1 = "Hello World";
String str2 = "How are you";
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
System.out.print(str1.charAt(i) + " ");
break;
}
}
}
}
}
Output:
H e o o r
Explanation: In this program, two nested for loops are used to iterate through each character of both strings. In the first loop, each character of the first string is taken one by one and in the second loop, each character of the second string is taken one by one. Then, the program checks if the current character of the first string is equal to the current character of the second string. If they are equal, the program prints the character and continue with the next characters.
In this example, the common element between the two strings is ‘H e o o r’.
It’s important to note that this approach has a time complexity of O(n^2) where n is the length of the strings. It is also case-sensitive, so if you want to find the common elements regardless of case, you can convert the original strings to lowercase or uppercase.

Question 27: How can you find the number of words in a given string in Java?
public class NumberOfWords {
public static void main(String[] args) {
String str = "This is a sample sentence for demonstration";
String[] words = str.split("\\s+");
int count = words.length;
System.out.println("The number of words in the string is: " + count);
}
}
Output:
The number of words in the string is: 7
Explanation: In this program, the split()
method is used to split the given string into an array of substrings based on the specified delimiter, which is one or more whitespace characters. The resulting array of substrings is then assigned to the words
variable. Then, the length of the words array is taken and assigned to the count variable and the count is printed out.
It’s important to note that this approach is using split method and it assumes that words are separated by one or more whitespace characters.
Also, you can use the split(CharSequence delimiter, int limit)
method which allows you to limit the number of splits. In this method, delimiter
is the delimiter to use and limit
is the maximum number of substrings to return.
You can also use the split(String regex, int limit)
method which allows you to split a string using any regular expression as a delimiter, so you can use it to split a string based on any kind of pattern you want.

Question 28: How can you find the index of the first non-repeated character in a given string in Java?
public class FirstNonRepeated {
public static int firstNonRepeated(String str) {
int[] count = new int[256];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
for (int i = 0; i < str.length(); i++) {
if (count[str.charAt(i)] == 1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "hello world";
int index = firstNonRepeated(str);
if (index == -1) {
System.out.println("All characters are repeated");
} else {
System.out.println("The index of the first non-repeated character is: " + index);
}
}
}
Output:
The index of the first non-repeated character is: 0
Explanation: In this program, an array of integers called count is used to count the number of occurrences of each character in the input string. Then, the program uses two nested loops to traverse through the string and check if each character is unique. If it is, the index of that character is returned. In the main method, the index is returned by the firstNonRepeated method and it is checked if the index is -1 which means all characters are repeated and if not it prints the index.
It’s important to note that this approach has a time complexity of O(n) where n is the length of the string and it is case-sensitive.
You can use a HashMap instead of an array to store the count of each character and this way it will be more efficient in terms of space.

Question 29: How can you find all the substrings of a given string in Java?
public class Substrings {
public static void allSubstrings(String str) {
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
System.out.println(str.substring(i, j));
}
}
}
public static void main(String[] args) {
String str = "hello";
allSubstrings(str);
}
}
Output:
h
he
hel
hell
hello
e
el
ell
ello
l
ll
llo
l
lo
o
Explanation: In this program, the allSubstrings method takes a string as a parameter and uses nested for loops to find all possible substrings of the given string. The outer loop starts at the first character of the string, and the inner loop starts one position after the current outer loop index. The program then prints the substring from the outer loop index to the inner loop index using the substring() method.
It’s important to note that this approach has a time complexity of O(n^2) where n is the length of the string.
Also, you can use the StringBuilder
class to store all the substrings and return them in a List instead of printing them.

Question 30: How can you use the replace()
method to replace a specific substring in a given string in Java?
public class Replace {
public static void main(String[] args) {
String str = "Hello World";
String replaced = str.replace("World", "Universe");
System.out.println("Original String: " + str);
System.out.println("Replaced String: " + replaced);
}
}
Output:
Original String: Hello World
Replaced String: Hello Universe
Explanation: In this program, the replace()
method is used to replace the substring “World” with “Universe” in the original string “Hello World”. The replaced string is then stored in the variable “replaced” and both the original and replaced strings are printed out.
It’s important to note that the replace()
method is case-sensitive, so if you want to replace a substring regardless of case, you can convert the original string to lowercase or uppercase using the toLowerCase()
or toUpperCase()
method before calling the replace method.
You can also use replaceAll(String regex, String replacement)
method where the first argument is the regular expression to match, and the second argument is the replacement string. You can also use replaceFirst(String regex, String replacement)
method which replaces only the first substring that matches the regular expression.
You can also use the replace()
method by passing the characters as arguments and it will replace all the occurrence of that character in the string.
It’s also important to mention that all of the above methods return a new string, rather than modifying the original string.

Follow us on YouTube for more Interview Program Questions on Java:
See you Soon!
Understanding the various string manipulation techniques and algorithms is crucial for any Java developer. By working through these frequently asked Java interview programs on strings, you will improve your understanding of strings and string manipulation in Java. You will learn how to find the length of a string, concatenate strings, compare strings, and much more. You will also learn about advanced string algorithms such as finding the first non-repeated character in a string, finding all the substrings of a given string, and finding all the possible combinations of a given string.
These programs will help you to prepare for your next Java interview and will improve your skills as a Java developer. Whether you are a beginner or an experienced Java developer, it is always a good idea to continue learning and practicing your skills.