5 Commonly Asked Java String Question in Selenium Interview
Nowadays interview’s conducted for Automation Engineers are having lots of Java Question. Sometimes the same question with small changes is asked which have multiple approaches to implement. One of the most favourite parts in java for Automation Engineers is String.
So here I am listing top 5 String questions asked in Interview and I am pretty sure you would find it helpful and will answer these question easily if asked by an interviewer.
But if you want to learn about String in Java, then I would suggest you, read Exploring String class in Java.
For more java tutorial I would suggest reading Java Tutorial.
Question 1: Write a program to reverse a string.
Input String: “This is the string to reverse”
Final Output: “esrever ot gnirts eht si sihT”
Answer:
The above question can be answered in many ways but here I am going to post two solutions. In which one is the simplest without giving much stress to mind just by using basic java concept and the second one is the most efficient that I have found(This solution can be used in reversing array as well)
Solution 1:
- First, we will receive the string (Either in form of variable or Scanner method)
- We will find the length of the string.
- We will use StringBuilder and will append the last character as the first character
Note: In all my program I am using TestNG (@Test).
import java.util.Scanner; import org.testng.annotations.Test; public class ReversingStringUsingLoop { @Test public void method1(){ System.out.println("Enter your String"); Scanner sc = new Scanner(System.in); String stringToReverse = sc.nextLine(); //Since String is immutable so going to take mutable alternative StringBuilder sb = new StringBuilder(); for(int i = stringToReverse.length()-1; i >=0; i-- ){ sb.append(stringToReverse.charAt(i)); } System.out.println("Reversed String "+ sb.toString()); } }
Here is the output on the console:
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse-32322801/testng-customsuite.xml Enter your String This is String To Reverse Reversed String esreveR oT gnirtS si sihT PASSED: method1 =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@626b2d4a: 11 ms [TestNG] Time taken by org.testng.reporters.XMLReporter@53bd815b: 6 ms [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 3 ms [TestNG] Time taken by org.testng.reporters.EmailableReporter2@41a4555e: 4 ms [TestNG] Time taken by org.testng.reporters.jq.Main@379619aa: 33 ms [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@71dac704: 3 ms
Solution 2:
- First, We will take String(In this example we will take the string in one variable ) and will convert String into StringBuilder.
- After conversion from String to StringBuffer, We will find the length of StringBuilder.
- Finally, we will swap characters from both ends until we will reach to mid of string.
Here is the code :
import org.testng.annotations.Test; public class ReverseStringFirstMethod { @Test public void Method1() { String stringFirstExample = "This is the string to reverse"; StringBuilder sb = new StringBuilder(stringFirstExample); int leng = sb.length(); for (int i = 0; i < leng / 2; i++) { char characterFirst = sb.charAt(i); int OtherEnd = leng - i - 1; sb.setCharAt(i, sb.charAt(OtherEnd)); sb.setCharAt(OtherEnd, characterFirst); } System.out.println("Final Reversed String :: " + sb.toString()); } }
Here is the output on the console:
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse-866377386/testng-customsuite.xml Final Reversed String :: esrever ot gnirts eht si sihT PASSED: Method1 =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@626b2d4a: 30 ms [TestNG] Time taken by org.testng.reporters.XMLReporter@53bd815b: 8 ms [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 5 ms [TestNG] Time taken by org.testng.reporters.EmailableReporter2@41a4555e: 8 ms [TestNG] Time taken by org.testng.reporters.jq.Main@379619aa: 72 ms [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@71dac704: 3 ms
A task for you:
Create a Function which takes String and gives output as reversed String.
Question 2: In the above question 1, we have been asked to reverse complete string character by character but at the same time interviewer might ask to reverse words in place of each character like this.
Input String: “This is the string to reverse”
Output String: “reverse to string the is This”
Answer:
This question again going to have many approaches but I am going to post the most optimal way where we will use the split function of string.
Solution:
- Take the String (In this example we are going to use a variable in place of Scanner class) and will break the string in an array using the split function of String using regular expression space “\\s”.
- We will find the length of the array and will iterate the array in reverse.
import org.testng.annotations.Test; public class ReverseWordsInString { @Test public void Method1() { String stringToReverse = "This is the string to reverse"; String[] brokenStringOnSpace = stringToReverse.trim().split("\\s"); StringBuilder sb = new StringBuilder(); int leng = brokenStringOnSpace.length; for (int i = leng - 1; i >= 0; i--) { sb.append(brokenStringOnSpace[i]); sb.append(' '); } System.out.println("Reversed String " + sb.toString()); } }
Here is the output on the console:
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse--1541558020/testng-customsuite.xml Reversed String reverse to string the is This PASSED: Method1 =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@626b2d4a: 24 ms [TestNG] Time taken by org.testng.reporters.XMLReporter@53bd815b: 6 ms [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 4 ms [TestNG] Time taken by org.testng.reporters.EmailableReporter2@41a4555e: 8 ms [TestNG] Time taken by org.testng.reporters.jq.Main@379619aa: 52 ms [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@71dac704: 3 ms
Question 3: Find duplicate characters in the provided String and also find the count of each duplicate character.
Input String: “Bharat”
Output: a
Answer:
If the above question was asked to find only the duplicate character then it was just a simple question that can be solved using the loop and some of the concept of an array. But as soon as the count is added with this question it becomes a very good question to solve.
Solution: For this first, we need to find duplicate value and its count where the character could be unique but its count might change with each iteration. So here we need to use hashmap where the key will remain constant and could not be duplicate but its value could be updated using its key.
- We will take the String.
- We will convert it in character array.
- We will define one hashmap where each character would act as a key and its count as value. Here we will check the presence of the key in the map and if the key exists we will increase the count of character or if it doesn’t present as the key in the map we will add it.
- In the end, we will print the key and value pair where the key would be duplicate character and value would be its count.
Note: Here I am assuming that lower case and upper case are being counted as same
But if you want to count both separately then replace this line of code
providedString.toLowerCase().toCharArray();
to this
providedString.toCharArray();
So here is the code
import java.util.HashMap; import java.util.Map; import java.util.Set; import org.testng.annotations.Test; public class DuplicateCharacterAndItsCountInString { @Test public void DuplicateCharacterAndItsCount(){ String providedString = "BharatBR"; Map<Character,Integer > duplicateCharMap = new HashMap<Character,Integer>(); char[] stringToCharArray = providedString.toLowerCase().toCharArray(); for(Character ch : stringToCharArray){ if(duplicateCharMap.containsKey(ch)){ duplicateCharMap.put(ch, duplicateCharMap.get(ch)+1); }else { duplicateCharMap.put(ch, 1); } } //printing charcter and duplicate value Set<Character> keys = duplicateCharMap.keySet(); for(Character ch : keys){ if(duplicateCharMap.get(ch) > 1) { System.out.println(ch +" is "+ duplicateCharMap.get(ch) +" Times in String"); } } } }
Here is the output on console(Pasting extract of the console)
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse--46882472/testng-customsuite.xml a is 2 Times in String PASSED: DuplicateCharacterAndItsCount
Question 4:
In Java write one program which finds duplicate words in the string and also find the count of the word.
Answer:
This question can be solved in the same ways as it was done for the duplicate character. The only thing that we need to incorporate is to split the string using space.
Solution:
- We will take the provided string and will split it using space in the string array.
- After this, we will compare each word from the place of word index+1 to the length-1.
- If we would find any value at both indexes in the array then we will increase the count.
- On the basis of the count, we will print the duplicate word.
Here is the code:
import org.testng.annotations.Test; public class FindDuplicateWordsInString { @Test public void findDuplicateWordWithCount(){ String providedString = "This is one String, which one need to be tested for duplicate word"; String[] brokenString = providedString.trim().split(" "); int count =1; for (int i =0; i < brokenString.length; i++){ for(int j = i+1; j < brokenString.length; j++){ if(brokenString[i].equals(brokenString[j])){ count = count+1; brokenString[j]="0"; } } if(count > 1) System.out.println(brokenString[i]+" is "+ count ); count=1; } } }
Output in the console.
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse-1960987409/testng-customsuite.xml one is 2 PASSED: findDuplicateWordWithCount
But if the interviewer asks for the count of each word present in the sentence then in place of this line of code
if(count > 1)
with this line
if(brokenString[i] != "0")
then out of the above code would be like this
[TestNG] Running: /private/var/folders/f4/81xh35vx7pg7gz4nknhlhqpr0000gn/T/testng-eclipse-183815565/testng-customsuite.xml This is 1 is is 1 one is 2 String, is 1 which is 1 need is 1 to is 1 be is 1 tested is 1 for is 1 duplicate is 1 word is 1 PASSED: findDuplicateWordWithCount
So we can see that the count of each word is given in output.
Question 5:
How you will find that these two Strings are equal.
String firstString = “Hello”
String secondString = new String(“Hello”)
Answer:
This is one of the trickiest question interviewers asks to check your knowledge of String.
To find the answer to this question read this article Learn String operations in Java using examples
Hope you like it if you like it then share it with your friends.
Reference Used:
Stack Overflow
This is a fantastic blog from which people can learn a lot. It is very informative and is explained in…
Thanks for sharing such knowledgeable Content on Automation testing, to know how to enhance the performance of ERP's like Oracle…
Thanks.. this list is much needed.
This one is also good to use. Thanks for sharing this.. Might be we can also add it in list…
How about youtube-dl?