In this article, we’ve covered the Top 10 Java programs commonly asked in Selenium interviews. Each program includes a clear explanation to help you understand the logic and improve your coding skills. Practice these programs regularly to strengthen your Java fundamentals and increase your chances of cracking Selenium automation interviews.
Watch YouTube Video Here: Top 10 Java Programs for Selenium Interviews | Most Asked Coding Questions with Answers
Question 1 – How to Reverse a String?
Answer:
public class ReverseString {
public static void main(String[] args) {
String str = “Selenium”;
String rev = “”;
for(int i = str.length()-1; i >= 0; i–) {
rev = rev + str.charAt(i);
}
System.out.println(“Original: ” + str);
System.out.println(“Reverse: ” + rev);
}
}
Explanation:
In this program, we have created a class named ReverseString and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, creating a string variable str with the value "Selenium" and an empty string variable rev to store the reversed result. It then uses a for loop that begins at the last character of the string (str.length() - 1) and moves backward to the first character (i >= 0). During each iteration, the str.charAt(i) method retrieves the current character and appends it to the rev string. By the time the loop finishes, all characters have been added in reverse order, resulting in "muineleS". Finally, the program prints both the original string and the reversed string to the console.
Question 2 – How to Check String is Palindrome or Not?
Answer:
Approach1:
public class Palindrome {
public static void main(String[] args) {
String str = "maddam";
String rev = "";
for(int i=str.length()-1; i>=0; i--) {
rev = rev + str.charAt(i);
}
if(str.equals(rev))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
Explanation for approach1:
In this program, we have created a class named Palindrome and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, a string variable str is initialized with the value "maddam" and another string variable rev is initialized as an empty string. A for loop starts from the last character of the string (str.length() - 1) and iterates backward to the first character. During each iteration, the charAt() method retrieves the current character and appends it to the rev string, thereby creating the reversed version of the original string. After the loop completes, the program compares the original string (str) with the reversed string (rev) using the equals() method. If both strings are equal, it means the string reads the same forward and backward, so the program prints “Palindrome”. Otherwise, it prints “Not Palindrome”. This is a simple and commonly asked Java interview program to check whether a given string is a palindrome.
Approach 2:
public class PalindromeCheck {
public static void main(String[] args) {
String str = "maddam";
int start = 0;
int end = str.length()-1;
while(start<=end) {
if(str.charAt(start) != str.charAt(end){
System.out.println(str+" is Not Palindrome");
break;
}
start++;
end--;
}
System.out.println(str+" is Palindrome");
}
}
Explanation for Approach 2:
In this program, we have created a class named PalindromeCheck and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, a string variable str is initialized with the value "maddam". Two integer variables, start and end, are then declared to point to the first (0) and last (str.length() - 1) characters of the string, respectively. The program uses a while loop that continues until the start index becomes greater than the end index. During each iteration, it compares the characters at the start and end positions using the charAt() method. If the characters are not equal, the program immediately prints that the string is not a palindrome and exits the loop using the break statement. If the characters match, the start index is incremented and the end index is decremented to compare the next pair of characters. If all corresponding characters match until the loop completes, the program prints that the string is a palindrome. This approach is more efficient than reversing the entire string because it compares characters directly from both ends and can stop as soon as a mismatch is found.
Question 3 – How to find Duplicate Characters in String?
Answer:
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "automation";
HashMap<Character,Integer> map = new HashMap<>();
for(char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c,0)+1);
}
for(char c : map.keySet()) {
if(map.get(c)>1)
System.out.println(c + " : " + map.get(c));
}
}
}
Explanation:
In this program, we have created a class named DuplicateCharacters and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, a string variable str is initialized with the value "automation". A HashMap<Character, Integer> named map is then created to store each character as the key and its occurrence count as the value. The program uses a for-each loop along with the toCharArray() method to iterate through each character of the string. During every iteration, the getOrDefault() method checks whether the character already exists in the HashMap. If the character is not present, it assigns a default count of 0; otherwise, it retrieves the existing count. The count is then incremented by 1 and updated in the HashMap using the put() method. After counting the occurrences of all characters, the program uses another for-each loop to iterate through the keys in the HashMap. For each character, it checks whether its count is greater than 1. If the condition is true, the program prints the character along with its frequency, identifying it as a duplicate character. This approach is efficient because it counts the occurrence of each character in a single pass and is commonly used in Java interviews to find duplicate characters in a string.
Question 4 – How to Count Number of Words in a String?
Answer:
public class WordCount {
public static void main(String[] args) {
String str = "Selenium WebDriver Java";
String words[] = str.split("\\s+");
System.out.println("Total words: " + words.length);
}
}
Explanation:
In this program, we have created a class named WordCount and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, a string variable str is initialized with the value "Selenium WebDriver Java". The program uses the split("\\s+") method to divide the string into individual words based on one or more whitespace characters, such as spaces, tabs, or multiple consecutive spaces. The resulting words are stored in a string array named words. After splitting the string, the program uses the length property of the array to determine the total number of words present in the string. Finally, it prints the total word count using the System.out.println() method. This is a simple and commonly asked Java interview program to count the number of words in a given string.
Question 5 – How to Find Largest Number in an Array?
Answer:
public class LargestNumber {
public static void main(String[] args) {
int arr[] = {10,25,5,50,15};
int max = arr[0];
for(int i=1;i<arr.length;i++) {
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest number: " + max);
}
}
Explanation:
In this program, we have created a class named LargestNumber and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, an integer array arr is initialized with the values {10, 25, 5, 50, 15}. A variable named max is then assigned the first element of the array (arr[0]) as the initial largest number. The program uses a for loop to iterate through the array starting from the second element (index 1). During each iteration, the current array element is compared with the value stored in max. If the current element is greater than max, the max variable is updated with the new larger value. This process continues until all the elements in the array have been checked. After the loop completes, the max variable contains the largest number in the array, which is then printed using the System.out.println() method. This is a simple and commonly asked Java interview program to find the largest element in an array.
Question 6 – How to Sort an Array Without Using Sort Method?
Answer:
public class ArraySort {
public static void main(String[] args) {
int arr[] = {6,2,8,5,3};
for(int i=0;i<arr.length;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int num: arr)
System.out.print(num + " ");
}
}
Explanation:
In this program, we have created a class named ArraySort and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, an integer array arr is initialized with the values {6,2,8,5,3}. The program uses two nested for loops to sort the array in ascending order. The outer loop selects one element at a time, while the inner loop compares the selected element with all the remaining elements in the array. During each comparison, if the current element is greater than the next element (arr[i] > arr[j]), the program swaps their positions using a temporary variable temp. This swapping process continues until all the elements are arranged in ascending order. After the sorting is complete, the program uses a for-each loop to iterate through the sorted array and prints each element. This is a simple sorting technique based on repeated comparisons and swapping, and it is a commonly asked Java interview program to demonstrate array sorting logic.
Question 7 – How to Swap Two Numbers Without a Third Variable?
Answer:
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 40;
a = a + b; // a = 50
b = a - b; // b = 10;
a = a - b; // a = 40;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Explanation:
In this program, we have created a class named SwapNumbers and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, two integer variables a and b are initialized with the values 10 and 40, respectively. The program swaps the values of these two variables without using a temporary variable by performing arithmetic operations. First, the values of a and b are added and stored in a (a = a + b), making a equal to 50. Next, the original value of a is obtained by subtracting the current value of b from a (b = a - b), so b becomes 10. Finally, the original value of b is obtained by subtracting the updated value of b from a (a = a - b), making a equal to 40. After the swapping process is complete, the program prints the updated values of a and b using the System.out.println() method. The final output is a = 40 and b = 10. This is a simple and commonly asked Java interview program to demonstrate how two numbers can be swapped without using an additional temporary variable.
Question 8 – How to Count Character Occurrence?
Answer:
public class CharacterCount {
public static void main(String[] args) {
String str = "selenium";
char search = 'e';
int count = 0;
for(int i=0;i<str.length();i++) {
if(str.charAt(i)==search)
count++;
}
System.out.println(search + " occurs " + count + " times");
}
}
Explanation:
In this program, we have created a class named CharacterCount and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, a string variable str is initialized with the value "selenium" and a character variable search is initialized with the character 'e', which is the character to be counted. An integer variable count is also initialized with 0 to keep track of the number of occurrences. The program uses a for loop to iterate through each character of the string from the first character to the last using the charAt() method. During each iteration, it compares the current character with the search character. If both characters are equal, the count variable is incremented by 1. This process continues until all the characters in the string have been checked. After the loop completes, the program prints the character along with the total number of times it appears in the string using the System.out.println() method. In this example, the character 'e' occurs 2 times. This is a simple and commonly asked Java interview program to count the occurrence of a specific character in a string.
Question 9 – How to Remove Duplicate Elements from Array?
Answer:
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int arr[] = {1, 1, 2, 3, 2, 4, 4, 1, 5};
HashSet<Integer> set = new HashSet<>();
for(int num: arr) {
set.add(num);
}
System.out.println(set);
}
}
Explanation:
In this program, we have created a class named RemoveDuplicates and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, an integer array arr is initialized with the values {1, 1, 2, 3, 2, 4, 4, 1, 5}, which contains duplicate elements. A HashSet<Integer> named set is then created to store only unique values because a HashSet does not allow duplicate elements. The program uses a for-each loop to iterate through each element of the array. During each iteration, the current element is added to the HashSet using the add() method. If the element is already present in the HashSet, it is ignored automatically, ensuring that only unique elements are stored. After all the elements have been processed, the program prints the contents of the HashSet using the System.out.println() method. The output contains only the unique elements from the array, such as [1, 2, 3, 4, 5] (the order may vary because HashSet does not maintain insertion order). This is a simple and commonly asked Java interview program to remove duplicate elements from an array using a HashSet.
Question 10 – Find Missing Number in an Array
Answer:
public class MissingNumberTwo {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 5, 6};
System.out.println(verifyArray(arr))
}
public static int verifyArray(int[] arr)
{
//Second approach
for(int i=0;i<arr.length-1;i++){
if(arr[i+1]-arr[i] != 1){
return arr[i]+1;
}
}
return -1;
}
}
Explanation:
In this program, we have created a class named MissingNumberTwo and defined the main() method, which is the entry point of the Java application and executes as soon as the program runs. Inside the main() method, an integer array arr is initialized with the values {1, 2, 3, 5, 6}, where the number 4 is missing. The program calls the verifyArray() method and passes the array as an argument to find the missing number. Inside the verifyArray() method, a for loop iterates through the array from the first element to the second-last element. During each iteration, the program compares the difference between two consecutive elements using the condition arr[i + 1] - arr[i] != 1. If the difference is not equal to 1, it indicates that a number is missing between those two elements. The method then returns the missing number by adding 1 to the current element (arr[i] + 1). If the loop completes without finding any missing number, the method returns -1, indicating that no missing element exists in the array. Finally, the main() method prints the returned missing number using the System.out.println() method. In this example, the output is 4. This is a simple and commonly asked Java interview program to find a missing number in a sorted array by comparing consecutive elements.