Selenium Automation | Java String Algorithms 16-20

As soon as you write Selenium Automation in your resume, interviewer is bound to give you a sheet of paper & ask write a Java program. Though Selenium doesn’t require extensive Java knowledge but still there is a set of basic Java programs that you should be able to write on-the-spot. Continuing on our Java interview series for Selenium Automation, this article covers five of the common Java String programs frequently asked in the basic technical interview. The questions are easy, but don’t forget to mark these java programs in your to do list before attending any entry-level technical interview for Selenium automation testing.

Flashback: Selenium Automation Interview questions | Java algorithms 11-15

Till now we have focused on numeric arrays. But they are most common. Everybody prepares that for the interview. In order to verify the OOPs concepts, interviewers are now asking about Java string programs instead. Why? Simple – because Java string programs are a bit level high than the simple arrays and it requires you to use different OOPs concepts like Java collections, arrays, String libraries, etc. Additionally, ‘String’ forms one of the important aspect of web applications as well as test data. This article will focus on five such Java String algorithms.

16. Find Duplicate characters in a String

One of the most common Java String algorithm is to identify duplicate characters in a string. Say you are given a string “Java2Novice” so letter ‘a’ and ‘v’ appear more than once. The algorithm is to identify & print these duplicate characters & their respective count.

The Logic: How do you identify duplicates? Simple – count the occurrence. Increment the occurrence every time same character is parsed. To keep a track of ‘Character – Count’, we will be using a HashMap. HashMap is a part of Java Collections and provides the basic implementation of Map interface. It stores the data in (Key, Value) pairs. To access a value you must know its key. HashMap is known as HashMap because it uses a technique called Hashing. In our example, the ‘Key’ would be the character and ‘Value’ will be its corresponding count.

package Java;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharacter {
        //function to find duplicate characters
        public static void findDuplicateChars(String str){
        //Creating an object of type HashMap
        Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
        //Convert the input string into a character array
        char[] chrs = str.toCharArray();
        //Parse each character of this array to update the count
        for(Character ch:chrs){
            //If character is already present in the Map, update the count to +1
            if(dupMap.containsKey(ch)){
                dupMap.put(ch, dupMap.get(ch)+1);
            } else {
                //Else insert the character in Map with initial value - 1
                dupMap.put(ch, 1);
            }
        }
        //Initialize a Set to read the HashMap populated above
        Set keys = dupMap.keySet();
        //Parse each character within the Set
        for(Character ch:keys){
            //If count value of character is greater than 1, print it.
            if(dupMap.get(ch) > 1){
                System.out.println(ch+"--->"+dupMap.get(ch));
            }
        }
    }
    public static void main(String a[]){
        findDuplicateChars("Java2Novice");
    }
}

As you might have guessed, below is the sequence of steps to be followed,

  1. Create a function to find duplicate characters.
  2. Create an object of type HashMap to store the Key-Value pair for each character within the string.
  3. Convert the input string into a character array.
  4. Parse each character of this array to update the count in HashMap.
  5. If character is already present in the Map, update the count to +1.
  6. Else insert the character in Map with initial value 1.
  7. Initialize a Set to read the HashMap populated above.
  8. Parse each character within the Set.
  9. If count value of character is greater than 1, print it.
  10. Call the above function within main() with input string as a parameter.

17. To check for a Palindrome String

Another common and simple Java String program is to identify whether the given string is a Palindrome or not. Palindrome: a word, phrase, or sequence that reads the same backwards as forwards, e.g. madam or nurses run.

The logic: How would you normally identify a palindrome string? Yeah! String Reverse = Actual String. Same is the programming logic. Just reverse the input string and then check to see if they are equal. Simple, right?

package Java;
public class Palindrome {
	public static void main(String[] args) {
		String str="MADAM";
		String revstring="";
		//For loop to reverse the input string.
		for(int i=str.length()-1;i>=0;--i){
		revstring +=str.charAt(i);
		}
		System.out.println(revstring);
		//Check if Reverse String is equal to the Original string.
		if(revstring.equalsIgnoreCase(str)){
		System.out.println("The string is Palindrome");
		}
		else{
		System.out.println("Not Palindrome");
		}
	}
}

18. Java – File Input/Output

Before moving on to the next Java String algorithm, let’s write a program to understand the Java input-output concept. Many a times, we need to read/write data to an external file. In these cases, it’s important that you practice the Java input-output operation.

  • BufferedReader: reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
  • File: abstract representation of file and directory path-names to denote an actual file-system object.
  • FileReader: meant for reading streams of characters. For reading streams of raw bytes, use FileInputStream.
  • Scanner: simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white-space.
package Java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class FileIO{
	public static void main(String[] args){
 		//Initializing a new File object with actual file path.
		File src = new File("C:\\Users\\deepanshuagarwal\\Documents\\Testing\\Java\\Practise.txt");
		try{
			//Initializing the Scanner with the File object.
			Scanner scanner = new Scanner(src);
                                           //Loop to Read the file one line at a time.
                                           while (scanner.hasNextLine()) {
	                             System.out.println(scanner.nextLine());
	                             }
	                             scanner.close();
		}
		catch(Exception e){
			System.out.println(e);
		}
		try {
		    //Initializing a BufferedReader Object with source file path.
		    BufferedReader in = new BufferedReader(new FileReader(src));
		    String str;
		    //Loop to read the file one line at a time.
		    while ((str = in.readLine()) != null)
		        System.out.println(str);
		    in.close();
		} catch (Exception e) {
		}
	}
}

19. Identify Repeated Words in a Java String

Similar to the first algorithm, this Java String program is to identify the repeated words within a string. The first program was to identify the ‘characters’, this is to identify the ‘words’. As you might have guessed, the logic would remain the same – count the occurrence. Increment the occurrence every time same word is parsed. To keep a track of ‘Word – Count’, use a HashMap.

package Java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class RepeatedWords {
	public static void main(String[] args){    
                            //Creating wordCountMap which hold words as keys and their occurrences as values.
		HashMap<String, Integer> wordCountMap = new HashMap<String, Integer>();
	    BufferedReader reader = null;
	    try{
                      //Creating BufferedReader object
	        reader = new BufferedReader(new FileReader("C:\\Users\\deepansagarwal\\Documents\\Deloitte\\Testing\\Java\\Practise.txt"));
            //Reading the first line into currentLine
            String currentLine = reader.readLine();
	        while (currentLine != null){    
                             //splitting the currentLine into words
	        	String[] words = currentLine.toLowerCase().split(" ");
                          //Iterating each word
	            for (String word : words){
                             //if word is already present in wordCountMap, updating its count
	            	if(wordCountMap.containsKey(word)){    
	            		wordCountMap.put(word, wordCountMap.get(word)+1);
	                }
                              //Etherwise inserting the word as key and 1 as its value
	                else{
	                	wordCountMap.put(word, 1);
	                }
	             }
                 //Reading next line into currentLine
                 currentLine = reader.readLine();
	        }
            //Getting the most repeated word and its occurrence
            String mostRepeatedWord = null;
	        int count = 0;
	        System.out.println(wordCountMap.size());
	        Set<Entry<String, Integer>> entrySet = wordCountMap.entrySet();
	        for (Entry<String, Integer> entry : entrySet){
	        	System.out.println(entry.getKey());
	        	if(entry.getValue() > count){
	                    mostRepeatedWord = entry.getKey();
	                    count = entry.getValue();
	            }
	        }
	        System.out.println("The most repeated word in input file is : "+mostRepeatedWord);
	        System.out.println("Number Of Occurrences : "+count);
	     } 
	     catch (IOException e){
	    	 e.printStackTrace();
	     }
	     finally{
	    	 try{
	                reader.close();//Closing the reader
	            }
	         catch (IOException e) 
	            {
	                e.printStackTrace();
	            }
	        }
	    }    
	}

20. Find Longest Sub-string with non-repeated Characters

The idea of this Java String algorithm is to identify the sub-strings within the input string such that it has no repeated character. For example, if ‘abcabcbb’ is the input string – then abc, bca, cab will be the longest sub-strings without any repeating characters.

package Java;
import java.util.HashSet;
import java.util.Set;
public class LongestSubStr {
	private Set subStrList = new HashSet();
	private int finalSubStrSize = 0;
	public Set getLongestSubstr(String input){
		//reset instance variables
		subStrList.clear();
		finalSubStrSize = 0;
		// have a boolean flag on each character ascii value
		boolean[] flag = new boolean[256];
		int j = 0;
		char[] inputCharArr = input.toCharArray();
		for (int i = 0; i < inputCharArr.length; i++) {
			char c = inputCharArr[i];
			if (flag[c]) {
				extractSubString(inputCharArr,j,i);
				for (int k = j; k < i; k++) {
					if (inputCharArr[k] == c) {
						j = k + 1;
						break;
					}
					flag[inputCharArr[k]] = false;
				}	
			} else {
				flag[c] = true;
			}
		}
		extractSubString(inputCharArr,j,inputCharArr.length);
		return subStrList;
	}	
	private String extractSubString(char[] inputArr, int start, int end){
		StringBuilder sb = new StringBuilder();
		for(int i=start;i<end;i++){ sb.append(inputArr[i]); } String subStr = sb.toString(); if(subStr.length() > finalSubStrSize){
			finalSubStrSize = subStr.length();
			subStrList.clear();
			subStrList.add(subStr);
		} else if(subStr.length() == finalSubStrSize){
			subStrList.add(subStr);
		}	
		return sb.toString();
	}
	public static void main(String a[]){
		LongestSubStr mls = new LongestSubStr();
		System.out.println(mls.getLongestSubstr("abcabcbb"));
	}
}

Hope these set of Java String programs were enough to intrigue your interest in googling and find some other Java String programs to solve. ‘Strings’ play an important role in both development as well as Testing – so it is important that Java String concepts are clear to you before attending the next interview. All the Best and Happy Testing!

 

Parikshram

Leave a Reply

Your email address will not be published.