TOP 10 Java String Interview questions and solutions for coding round
How can you print duplicate characters out of a string?
We say a character is a duplicate if it appears more than once in the string. Here we use the iteration (traversal) method to solve the problem.
First, we take the starting character from the string and check with the rest of the characters. If both characters match we print them on the console.
Once we found the duplicate character, update the array position to 0 to avoid rechecking on iteration.
If you wish to print the number of times a character appears in a string, then print the count value along with it. The Count variable stores how frequently a character appears in a string.
public class DuplicateCharacters {
public static void main(String[] args) {
String s = "Great responsibility";
usingTraversal(s);
}
public static void usingTraversal(String s) {
char[] characters = s.toCharArray();
int length = s.length;
int count = 1;
for (int i = 0; i<length; i++) {
count = 1;
for (int j = i + 1; j<length; j++) {
if (characters[i] == characters[j] && characters[i] != ' ') {
count++;
characters[j] = '0';
}
}
if (count > 1 && characters[i] != '0') {
System.out.println(c[i]);
}
}
}
}
Print out the duplicate characters and their frequency
This question is the same as the above one except here we are asked to print the frequency (number of times a character occurs in the string).
The logic remains the same, but here we need to print the frequency additionally. We can use the map to solve this question.
A map is a key-value pair where the character is the key and frequency is the value.
We iterate through the characters and perform the steps below.
- If a character is already present on the map, increase the frequency and update the map.
- If a character is not present on the map, add the character to the map with frequency as 1.
import java.util.HashMap;
import java.util.Map;
public class DuplicateCharacters {
public static void main(String[] args) {
String s = "Great responsibility";
usingMapHash(s);
}
public static void usingMapHash(String str) {
Map<Character, Integer> map = new HashMap<>();
int len = str.length();
for (int i = 0; i<len; i++) {
char c = str.charAt(i);
if (c != ' ') {
if (map.containsKey(c)) {
int temp = map.get(c) + 1;
map.put(c, temp);
} else {
map.put(c, 1);
}
}
}
System.out.println(map);
}
}
Search for anagrams between two strings
Anagrams are words formed by rearranging the letters in a word or phrase in a different order. For example, we can say cat and act are anagrams of each other because both have the same letters but in a different order.
import java.util.Arrays;
public class AnagramString {
public static void main(String[] args) {
isAnagram("Debit card", "Bad credit");
isAnagram("cat", "act");
}
public static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
}
Check whether a string only contains digits
We say a string contains only digits when all the characters are numeric and no alphabet is present.
We can solve this problem using the traversal method. First, we iterate through the string performing the following logic.
- Depending on whether the character at index is numeric or not, increase the numberOfDigit value.
- If the number of digits is equal to the string length then our string contains only digits.
public class OnlyDigits {
public static void main(String[] args) {
System.out.println(usingTraversal("yyyY"));
System.out.println(usingTraversal("y1234"));
System.out.println(usingTraversal("y123Y"));
System.out.println(usingTraversal("123Y"));
System.out.println(usingTraversal("21233"));
}
public static boolean usingTraversal(String str) {
System.out.println("string : " + str);
int length = str.length();
int numberOfDigit = 0;
for (int i = 0; i<length; i++) {
if (str.charAt(i) >= '0' && str.charAt(i)<= '9') {
numberOfDigit++;
}
}
return (length == numberOfDigit);
}
}
Using Java regular expressions.
Let's see how we can solve strings containing only numbers using regular expressions. The String class has predefined match methods that check the string value against the given regular expression.
The "[0-9]+" here is a regular expression, which means our string can only contain digitals. If our string matches the pattern, the matches method returns true. If not, it returns false.
public static void usingRegularExp(String str) {
boolean result = str.matches("[0-9]+");
System.out.println("string : " + str);
System.out.println("Contain only digits? : " + result);
}
Using Java 8 streams
We can also solve the above problems using Java 8 stream features.
Here we have converted our string to a list of characters and used the Java 8 stream for iteration.
If all elements of the list match the condition, the allMatch method returns true. If any element fails to match, it returns false.
In the following code, we have a method called Character.isDigit that returns true if the character is numeric, otherwise false.
public static void usingJava8Stream(String str) {
List<String> characters = Arrays.asList(str.split(""));
boolean isContainDigits = characters.stream().allMatch(s -> Character.isDigit(s.charAt(0)));
System.out.println("string : " + str);
System.out.println("Contain only digits? : " + isContainDigits);
}
Reverse a string by using recursion
In Java, recursion refers to a function that calls itself, ending only when it meets the exit condition. Here we are asked to solve the string by calling the recursion function.
For example, if "abcd" is the input, the reverse string would be "dcba".
If the string is not empty, get the last character using the charAt method and make a recursion call with the string without the last character. Once we reach an empty string we end the recursion call.
public class StringReverse {
public static void main(String[] args) {
String s = reverseRecursion("abcd");
System.out.println(s);
}
public static String reverseUsingRecursion(String s) {
String reverse = new String();
int len = s.length();
if (!s.isEmpty()) {
reverse = reverse + s.charAt(len - 1) + reverseUsingRecursion(s.substring(0, len - 1));
} else {
return "";
}
return reverse;
}
}
Count the occurrence of vowels, consonants, numbers, and symbols in the string
The vowels (a, e, i, o, u) of the alphabet are called vowels, and the rest of the alphabet is called consonants.
In this program, we will count the number of vowels, consonants, numbers, and symbols in a string using the iterate method.
First, we iterate through our string and get characters at each index using the charAt method.
Using the Character.isAlphabetic method we determine whether the character is an alphabet or not. If it’s an alphabet, we check whether it’s vowels.
If it's vowels then increase the count of vowels otherwise increase the count of consonants.
We use the isDigit method in Character class to check whether our character is a number or not, if it’s a number then increase the count of digits.
If the character does not belong to the number alphabet, increase the count of symbols.
public class CountOccureance {
public static void main(String[] args) {
String str = "Bharath1234@Gmail.com";
int vowelsCount = 0;
int consonantsCount = 0;
int symbolsCount = 0;
int numberCount = 0;
for (int i = 0; i<str.length(); i++) {
char letter = str.charAt(i);
if (Character.isAlphabetic((int) letter)) {
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowelsCount++;
} else {
consonantsCount++;
}
} else if (Character.isDigit(letter)) {
numberCount++;
} else {
symbolsCount++;
}
}
System.out.println("Vowels = " + vowelsCount);
System.out.println("Consonants = " + consonantsCount);
System.out.println("Numbers = " + numberCount);
System.out.println("Symbols = " + symbolsCount);
}
}
String of palindromes
A palindrome is a word that is the same in both forward and reverse directions. For example, the word madam reversed backward is also madam. Therefore, madam is a palindrome.
In the below program, we have used the StringBuffer class to reverse the given word and compare the reversed string with the original string. If both are equal, the string is a palindrome.
public class Palindrome {
public static void main(String[] args) {
isPalindrome("madam");
isPalindrome("dad");
isPalindrome("1881");
isPalindrome("Loveyou");
}
public static void isPalindrome(String str) {
StringBuffer reversed = new StringBuffer(str);
reversed = reversed.reverse();
boolean isPalindrome = str.equals(reversed.toString());
System.out.println("is " + str + " a palindrome " + isPalindrome);
}
}
Sum of integers in string
In this problem, we will get numeric values in string format. We need to add up all the numbers and give the total, for example, if a given string is 1234 then the sum of integers is 10. This is because when we add all numbers together we get a total of 10.
In some cases, we may get a string like 1a2b3c4d. Here we have to ignore all letters and consider only the number present in the string.
In the below program,
First, we have converted string to character array and assigned sum = 0.
Iterated through the character array if the character is a digit, add with sum.
To convert a character into an integer value we have used the Character.getNumericValue method which returns an integer value for a given character.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SumOfIntegers {
public static void main(String[] args) {
sum("1234");
sum("12Y3Y4A");
}
public static void sum(String num) {
char[] numbers = num.toCharArray();
int sum = 0;
for (char number: numbers) {
if (Character.isDigit(number)) {
sum = sum + Character.getNumericValue(number);
}
}
System.out.println("Sum of " + num + " = " + sum);
}
}
Swap String
we have to swap string values for e.x we have two strings s1 = “Hello” and s2= “World” after swapping the values get swapped so now s1 will have “World” value and s2 will have “Hello”.
Here we have solved the problem using a third variable named temp which contains the concatenated value of s1 and s2 together.
Using the temp variable we have will swap the values, substring method give the part of the string.
So substring from 0 to length of s1 assigned to s2 likewise substring from a length of s1 ( if you don’t tell the end index then It take the last index as the end index) assigned to s1.
public class SwapString {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
System.out.println("Before swapping");
System.out.println(s1 + " " + s2);
String temp = s1 + s2; //Hello + World
int len1 = s1.length();
s2 = temp.substring(0, len1); // Hello
s1 = temp.substring(len1); // World
System.out.println("After swapping");
System.out.println(s1 + " " + s2);
}
}
Sort String
We can solve the problem in two ways by using the traversal method and the Arrays sort method.
Using for Loop
Here we have converted string to character array and check whether the character[i] is greater than the character[j] if yes then swap the value using the temporary variable.
public class SortString {
public static void main(String[] args) {
sort("adcbfehg");
}
public static void sort(String value) {
char[] letters = value.toCharArray();
for (int i = 0; i <= letters.length; i++) {
for (int j = i + 1; j <= letters.length - 1; j++) {
if (letters[i] >= letters[j]) {
char temp = letters[i];
letters[i] = letters[j];
letters[j] = temp;
}
}
}
String sortedValue = new String(letters);
System.out.println(sortedValue);
}
}
Using the Arrays Sort method
Here we have converted string to character array and used the Arrays.sort method to sort the character array.
we cannot use the below logic in the interview if they asked to solve it without using the library method.
import java.util.Arrays;
public class SortString {
public static void main(String[] args) {
sortUsingLibrayMethod("adcbfehg");
}
public static void sortUsingLibrayMethod(String value) {
char[] letters = value.toCharArray();
Arrays.sort(letters);
String sortedValue = new String(letters);
System.out.println(sortedValue);
}
}
Sort String in descending order
we have to sort string in descending order (highest to lowest value). first, we use the iteration method to sort the string.
we used the above code but only in the if condition instead of checking greater than we have used lesser than to sort string in descending order.
public class SortStringInDesending {
public static void main(String[] args) {
sort("13574826");
}
public static void sort(String value) {
char[] letters = value.toCharArray();
for (int i = 0; i <= letters.length - 1; i++) {
for (int j = i + 1; j <= letters.length - 1; j++) {
if (letters[i] < letters[j]) {
char temp = letters[i];
letters[i] = letters[j];
letters[j] = temp;
}
}
}
String sortedValue = new String(letters);
System.out.println(sortedValue);
}
}
For more practice try to solve out below problems.
Coding Bat String Problems and Solutions
Coding Bat Advanced String Problems and Solutions