Java String is an important part of the Java Interviews. Below I have given the top 12 Java String programs (coding examples) that you will be asked in your Java Interview. Also, I have provided the required explanation to understand the program in a better way.
Also, I have written a blog about the Top 20 Java String Interview Question And Answers. This post explains the top 20 theoretical questions and answers about the string. Please consider reading this blog before trying the following coding examples.
1. How to convert an array to string in Java?
Sometimes in a program, you have to convert an existing array to string.
There is a total of 4 ways we can convert an array to string.
1. Arrays.toString()
method
Arrays.toString()
method returns the string of the input array. The returned string is a string representation of the input array.
The returned string contains the elements of the input array separated by the comma and followed by space. Also, the element is surrounded by ‘[]’.
2. StringBuilder.append()
method
In this way, we are appending each element of the input array to an instance of the StringBuilder
class using the append()
method.
By using this method, we can get the string from the elements of the input array connected without spaces.
3. String.Join()
method
Java 8 and above, you can use the join()
method of the String
class converts an array to string.
4. Collectors.joining()
method
Java 8 provides the Stream
API. You can use the joining()
method of the Collectors
class to convert an array to string.
The following program shows you how to convert an array to string.
import java.util.stream.Collectors; /* * A Java program to convert an array to string. */ public class ArrayToString { public static void main(String[] args) { String[] stringArray = { "My", "name", "is", "Gaurav", "!" }; // 1. Using the Arrays.toString() method String string1 = convertArrayToStringUsingToString(stringArray); System.out.println("An array converted to string using Arrays.toString(): " + string1); // 2. Using the StringBuilder.append() method String string2 = convertArrayToStringUsingAppend(stringArray); System.out.println("An array converted to string using StringBuilder.append(): " + string2); // 3. Using the String.join() method String string3 = convertArrayToStringUsingJoin(stringArray); System.out.println("An array converted to string using String.join(): " + string3); // 4. Using the Collectors.joining() method String string4 = convertArrayToStringUsingJoining(stringArray); System.out.println("An array converted to string using Collectors.joining(): " + string4); } // 1. Using the Arrays.toString() method public static String convertArrayToStringUsingToString(String[] stringArray) { return Arrays.toString(stringArray); } // 2. Using the StringBuilder.append() method public static String convertArrayToStringUsingAppend(String[] stringArray) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < stringArray.length; i++) { stringBuilder.append(stringArray[i]); } return stringBuilder.toString(); } // 3. Using the String.join() method public static String convertArrayToStringUsingJoin(String[] stringArray) { String str = String.join(" ", stringArray); return str; } // 4. Using the Collectors.joining() method public static String convertArrayToStringUsingJoining(String[] stringArray) { String str = Arrays.stream(stringArray).collect(Collectors.joining()); return str; } }
The output of the above program will be,
An array converted to string using Arrays.toString(): [My, name, is, Gaurav, !] An array converted to string using StringBuilder.append(): MynameisGaurav! An array converted to string using String.join(): My name is Gaurav ! An array converted to string using Collectors.joining(): MynameisGaurav!
2. How to check if two strings are the same ignoring their cases?
You can check if two strings are the same or not using the equals()
method of the String. There is a special version of the equals()
method which ignores the cases i.e. equalsIgnoreCase()
Below I have given the program to check if the string is the same or not using the equalsIgnoreCase()
.
public class CheckStringContentIgnoringCases { public static void main(String[] args) { String firstString = "My Name Is Gaurav!"; String secondString = "my name is gaurav!"; // Case 1 // Check if the strings are same using the simple equals() method System.out.println("checking using equals() method : " + firstString.equals(secondString)); // Case 2 // Check if the strings are same using the equalsIgnoreCase() method System.out.println("checking using equalsIgnoreCase() method : " + firstString.equalsIgnoreCase(secondString)); } }
The output of the above program will be,
checking using equals() method : false checking using equalsIgnoreCase() method : true
In the first case, we are comparing the strings using the equals()
method.
It is printing false
because even if both the string contains the same sentence, there is a difference between the case.
In firstString
every word starts with a capital letter while in secondString
, every letter is in a small case.
In the second case, we are comparing the strings using the equalsIgnoreCase()
method.
It will compare the content of the firstString
and secondString
ignoring the case hence it is printing true
.
3. How to print duplicate characters from the string?
In this program, you have to found and print the duplicate characters from the given input string.
Sometimes you will be asked to print the number of times that duplicate characters came in the string. So we are printing their count too.
Below I have given a program that prints the duplicate characters from the string with its count.
import java.io.CharConversionException; import java.util.ArrayList; public class FindDuplicates { public static void main(String[] args) { String inputString = "My name is Guarav Kukade!"; printDuplicates(inputString); } public static void printDuplicates(String inputString) { // count int count = 0; // a temp list of ch for which we have already printed the count ArrayList<Character> charList = new ArrayList<>(); for (int i = 0; i < inputString.length(); i++) { char ch = inputString.charAt(i); // count the number of occurrences of the char ch in inputString for (int j = 0; j < inputString.length(); j++) { if (inputString.charAt(j) != ch) { continue; } count++; } // check if we have already printed for ch if (!charList.contains(ch)) { // check if count is more than 1 i.e. duplicate and char should not be space if (count > 1 && ch != ' ') { System.out.println("Char: " + ch + ", Count: " + count + " times."); charList.add(ch); } } // set counter to zero for next ch count = 0; } } }
The output of the above program will be,
Char: a, Count: 4 times. Char: e, Count: 2 times. Char: u, Count: 2 times.
4. How to check if two strings are anagrams of each other?
We can say if two strings are an anagram of each other if they contain the same characters but at different orders.
Ex. army & mary
This question requires a good understanding of the Java String class and Java arrays.
The following program shows how can we check if the given strings are an anagram of each other.
import java.util.Arrays; public class CheckAnagram { public static void main(String[] args) { String firstString = "Army"; String secondString = "mary"; System.out.println("Check if the firstString and secondString is anagram of each other: "+ isAnagram(firstString, secondString)); } public static boolean isAnagram(String firstString, String secondString){ char[] firstStringCharArray = firstString.toLowerCase().toCharArray(); char[] secondStringCharArray = secondString.toLowerCase().toCharArray(); Arrays.sort(firstStringCharArray); Arrays.sort(secondStringCharArray); return Arrays.equals(firstStringCharArray, secondStringCharArray); } }
The output of the above program will be,
Check if the firstString and secondString is anagram of each other: true
In the above program, the isAnagram()
method took two string firstString
and secondString
as an input parameter.
We are converting these string into the character array.
Also, we are applying the toLowerCase()
method to the strings to make sure every character of the char array should be in lower case.
Once we got both the array, we are sorting them using the Arrays.sort()
method.
Arrays.sort()
method sort the specified array into ascending numerical order.
Finally, we will check if the arrays are equals using Arrays.equals()
method.
If they are equal, that means they are an anagram of each other.
If they are not equal, then they are not an anagram of each other.
5. How to reverse a string in Java without using the reverse method?
This is the common question asked in the java interviews. We know, we can easily reverse the java string using the `reverse()` method of the StringBuilder
class.
You will be asked to reverse the string without using any pre-defined library reverse method.
Below, I have given a program to reverse the string without using the reverse method.
/** * A Java program to reverse a string. * * We are using 'charAt()' method of the String class to get all char and * arrange it in descending order to get a reverse string. * */ public class ReverseString { public static void main(String[] args) { String name = "GauravKukade"; String reversedString = ""; for (int i = name.length() - 1; i >= 0; i--) { reversedString = reversedString + name.charAt(i); } System.out.print("The reversed string of the '" + name + "' is: "); System.out.println(reversedString); } }
The output of the above program will be,
The reversed string of the 'GauravKukade' is: edakuKvaruaG
In the first method, we are initializing an empty string variable, reversedString
.
You can use the charAt()
method of the String class to get the character at any particular index of the string.
We are getting the characters of the inputString
one by one in reverse order and appending it to the reversedString
.
Finally, we are returning the reversedString
.
In the second method, we are converting the inputString
to the characters array using the toCharArray()
method of the String class.
Once we got the array, we are appending the characters from the characters array stringCharArray
to reversedString
one by one in reverse order.
And finally, we are returning the reversedString
.
6. How to count the occurrence of the given character in a string?
Sometimes you will be asked to count the number of occurrences of any particular character in the given input string.
Below, I have given the program for the same.
public class CountCharacter { public static void main(String[] args) { String inputString = "coderolls"; char ch = 'o'; int count = 0; for (int i = 0; i < inputString.length(); i++) { if (inputString.charAt(i) == ch) { count++; } } System.out.println("The character '" + ch + "' found " + count + " times in a string '" + inputString + "'."); } }
The output of the above program will be,
The character 'o' found 2 times in a string 'coderolls'.
In the above program, we are checking the number of occurrences for the character ch in the string inputString.
If the character ch found in the inputString
, we are increasing the count by one.
Finally, we are printing the character count using the print statement.
Also, you can use the continue
statements to count the occurrences of a character in a string. The continue
statement is one of the control flow statements in Java.
Below I have given a program that uses the continue statement to solve the above question.
public class CountCharacterUsingContinue { public static void main(String[] args) { String inputSttring = "Gaurav Kukade"; int count = 0; for (int i = 0; i < inputSttring.length(); i++) { if (inputSttring.charAt(i) != 'a') { continue; } count++; } System.out.println("We found 'a' in the inputString '" + inputSttring + "', " + count + " times."); } }
The output of the above program will be,
We found 'a' in the inputString 'Gaurav Kukade', 3 times.
7. How to convert string to integer?
In the java program, many times, we have to convert a string to an int.
We can convert string to an integer using Integer.parseInt()
method as well as Integer.valueOf()
method.
Below I have given a java program to convert the String str
to int result
.
/* * A Java program to convert the String to an integer. */ public class StringToInteger { public static void main(String[] args) { String str = "1234"; int result = Integer.parseInt(str); // using Integer.parseInt() // int result2 = Integer.valueOf(str); //using Integer.valueOf() System.out.println("The converted int is: " + result); } }
The output of the above program will be,
The converted int is: 1234
In the above program, we have to make sure that String str
should not contain any characters other than the decimal digit.
If str
contains any character other than digits, it will throw the NumberFormatException
.
8. How to check if a string is a palindrome?
If the string is similar from the starting as well as the ending, then we can say that the string is a palindrome.
For example. madam, radar, etc.
I have given a program below which checks if the given string is palindrome or not.
/* * A Java program to check if a string is palindrome or not. */ public class PalindromeString { public static void main(String[] args) { String inputString = "madam"; String reversedString = reverseString(inputString); if (inputString.equals(reversedString)) { System.out.println("The inputString '" + inputString + "' is a palindrome String."); } else { System.out.println("The inputString '" + inputString + "' is not a palindrome String."); } } // a method t reverse the string public static String reverseString(String str) { String reversedString = ""; for (int i = str.length() - 1; i >= 0; i--) { reversedString += str.charAt(i); } return reversedString; } }
The output of the above program will be,
The inputString 'madam' is a plaindrome String.
In the above program, we are getting the reversed string of the inputString
.
If the reversedString
and the inputString
is the same, then the string is a palindrome.
9. Write a program to remove given characters from the string?
The below program removes any specified character from the given string.
/* * A Java program to remove characters from the String. */ public class RemoveCharacters { public static void main(String[] args) { String inputString = "GauravKukade"; char ch = 'a'; String result = removeCharacters(inputString, ch); // pass the inputString and char you want to remove System.out.println("After removing character '" + ch + "' from the inputString '" + inputString + "' the result will be: \n" + result); } // a method to remove any particular char from the string public static String removeCharacters(String str, char ch) { String result = str.replace("a", ""); return result; } }
The output of the above program will be,
After removing character 'a' from the inputString 'GauravKukade' the result will be: GurvKukde
In the above program, we are getting character at any particular index using the charAt()
method.
If this character equals the specified character, we will remove this character from the string.
10. How to count the number of words in a given string sentence?
This is a nice question.
You can count the number of words from a given string using the library method like the split()
method of the String class, and also you can use the StringTokenizer
class to count the number of words.
If the interviewer asks you to create a new method to count the number of words in the sentence, we will see that way too.
The method to count the number of words using the split()
method is given below.
public static int countWordsUsingSplit(String inputString) { String[] stringArray = inputString.split("\\s+"); // splitting the string using space/spaces return stringArray.length; // returning the length of the array i.e number of words in the string }
In the above method, we are using the "\\s+"
for splitting because of the +
operator adds in if the string contains more than one space in between the string.
The method to count the number of words using the StringTokenizer
class is given below.
public static int countWordsUsingStringTokenizer(String inputString) { if (!inputString.isEmpty()) { StringTokenizer stringTokenizer = new StringTokenizer(inputString); // create StringTokenizer using the // inputString return stringTokenizer.countTokens(); // returning the number of tokens i.e. number of words } return 0; }
In the above program, we are creating a StringTokenizer
using the inputString
and simply returning the number of tokens using countTokens()
method.
When we create tokens using the StringTokenizer
, it delimits the inputString
using the space character.
The custom method to count the number of words is given below,
public static int countWords(String inputString) { int wordCount = 0; int endOfString = inputString.length() - 1; String str = inputString.trim(); // making sure that string should not have any spaces at the starting and // ending for (int i = 0; i < inputString.length(); i++) { if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' ') { wordCount++; } else if (str.charAt(i) == ' ' && str.charAt(i++) == ' ') { // if there is more than one space in between // string i++; } else if (i == endOfString) { // matching the first missing word wordCount++; } } return wordCount; }
Below, I have given the complete program which counts the number of words from the given input string using all the three input methods.
/* * A Java program to count the words form the string. */ import java.util.StringTokenizer; public class CountWordsUsingSplit { public static void main(String[] args) { String inputString = "Arise! Awake! and stop not until the goal is reached."; System.out.println("The input string is : \n" + inputString + "\n"); System.out.println("Count words using split() method: " + countWordsUsingSplit(inputString)); System.out.println("Count words using StringTokenizer class: " + countWordsUsingStringTokenizer(inputString)); System.out.println("Count words using custom method: " + countWords(inputString)); } // method to count words using the split() method public static int countWordsUsingSplit(String inputString) { String[] stringArray = inputString.split("\\s+"); // splitting the string using space/spaces return stringArray.length; // returning the length of the array i.e number of words in the string } // method to count words using the StringTokenizer class public static int countWordsUsingStringTokenizer(String inputString) { if (!inputString.isEmpty()) { StringTokenizer stringTokenizer = new StringTokenizer(inputString); // create StringTokenizer using the // inputString return stringTokenizer.countTokens(); // returning the number of tokens i.e. number of words } return 0; } // custom method to count the words from the string public static int countWords(String inputString) { int wordCount = 0; int endOfString = inputString.length() - 1; String str = inputString.trim(); // making sure that string should not have any spaces at the starting and // ending for (int i = 0; i < inputString.length(); i++) { if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' ') { wordCount++; } else if (str.charAt(i) == ' ' && str.charAt(i++) == ' ') { // if there is more than one space in between // string i++; } else if (i == endOfString) { // matching the first missing word wordCount++; } } return wordCount; } }
The output of the above program will be,
The input string is : Arise! Awake! and stop not until the goal is reached. Count words using split() method: 10 Count words using StringTokenizer class: 10 Count words using custom method: 10
11. How to reverse the words from the given string sentence?
In the above program we have seen, how can we count the number of words from the input string.
We can use the same logic to get the words. Once we have a word, we can reverse it.
And when we connect these reversed words properly, we will have a string with reversed words.
I have given a full program to reverse the words from the string.
/* * A java program to reverse the words from the given string. */ public class ReverseWordsFromString { public static void main(String[] args) { String inputString = "Arise! Awake! and stop not until the goal is reached"; String outputString = reverseWordsFromString(inputString); System.out.println("The string with the reversed word is : \n" + outputString); } public static String reverseWordsFromString(String inputString) { String[] wordsArray = inputString.trim().split("\\s+"); String stringWithReversedWords = ""; for (String word : wordsArray) { stringWithReversedWords += reverseWord(word) + " "; } return stringWithReversedWords.trim(); } public static String reverseWord(String word) { String reversedWord = ""; for (int i = word.length() - 1; i >= 0; i--) { reversedWord += word.charAt(i); } return reversedWord; } }
The output of the above program will be,
The string with the reverse word is : !esirA !ekawA dna pots ton litnu eht laog si dehcaer
12. How to swap two strings without using the third variable?
We can swap two string without using a third variable. We are going to use a substring method to achieve the same.
Below I have given a program that swaps the two strings without using the third string.
/* * A java program to swap strings without using the third variable. */ public class SwapStrings { public static void main(String[] args) { String firstString = "one"; String secondString = "two"; System.out.println("Before swapping...."); System.out.println("The first String = " + firstString); System.out.println("The second String = " + secondString); firstString = firstString + secondString; // step 1 secondString = firstString.substring(0, (firstString.length() - secondString.length())); // step 2 firstString = firstString.substring(secondString.length()); // step 3 System.out.println("\nAfter swapping...."); System.out.println("The first String = " + firstString); System.out.println("The second String = " + secondString); } }
The output of the above program will be,
Before swapping.... The first String = one The second String = two After swapping.... The first String = two The second String = one
In the above program, I have marked the steps.
In the first step, we are just adding both the strings and storing it in a firstString
.
Now firstString
will be “GauravKukade”.
In the second step, the substring()
method with the first parameter ‘0’ and last parameter (firstString.length() - secondString.length())
will give us the first string. We are assigning it to secondString
.
In the last step, we will use the substring()
method with only one parameter, secondString.length()
. (remember now the value of the secondString
is “Gaurav”.) It will give us the second string, and we can assign it to the firstString
.
Hello, Guarav, we’ve got a lot of negative feedbacks regarding a formatting of your code on reddit
https://www.reddit.com/r/programming/comments/fjhpz4/top_12_string_programs_for_your_next_java/
https://www.reddit.com/r/java/comments/fjhpn1/top_12_string_programs_for_your_next_java/
Can you fix it?