TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: 15 Java Coding Questions for Testers
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

15 Java Coding Questions for Testers

Last updated: Feb 25, 2024 2:21 am
By Meenakshi Agarwal
Share
12 Min Read
Java Coding Questions for Software Testers
Java Coding Questions for Software Testers.
SHARE

Java and Selenium are the best automation tools for QA. And these skills are a must for every QA engineer involved in test automation. Hence, in this post, we’re presenting a set of 15 Java coding questions for testers frequently asked during job interviews.

Top Java Coding Questions for Testers

To grow in a testing job, testers should also have a working knowledge of programming languages such as Java or Python. These skills not only help them in doing automation testing but also improve the way they deal with the product or issues

Set-1 of Java Coding Interview Questions for Testers

It is important to realize and it’s a fact that most IT companies offer high salaries to test automation developers as they know how to program. So, explore these Java coding questions specially designed for testers.

Question#1: Write code to filter duplicate elements from an array and print as a list.

Ans.

package simple.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class findDuplicates {

  public static void main(String[] args) {

    ArrayList < String > list = new ArrayList < String > ();

    // Form a list of numbers from 0-9.
    for (int i = 0; i < 10; i++) {
      list.add(String.valueOf(i));
    }

    // Insert a new set of numbers from 0-5.
    for (int i = 0; i < 5; i++) {
      list.add(String.valueOf(i));
    }

    System.out.println("Input list : " + list);
    System.out.println("\nFiltered duplicates : " + processList(list));
  }

  public static Set < String > processList(List < String > listContainingDuplicates) {

    final Set < String > resultSet = new HashSet < String > ();
    final Set < String > tempSet = new HashSet < String > ();

    for (String yourInt: listContainingDuplicates) {
      if (!tempSet.add(yourInt)) {
        resultSet.add(yourInt);
      }
    }
    return resultSet;
  }
}

Question#2: Write code to sort the list of strings using Java collection.

Ans.

package simple.test;

import java.util.Arrays;

public class sortStrings {

  public static void main(String[] args) throws Exception {

    String[] inputList = {
      "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "aug", "Sep", "Oct", "nov", "Dec"
    };

    // Display input un-sorted list.
    System.out.println("-------Input List-------");
    showList(inputList);

    // Call to sort the input list.
    Arrays.sort(inputList);

    // Display the sorted list.
    System.out.println("\n-------Sorted List-------");
    showList(inputList);

    // Call to sort the input list in case-sensitive order.
    System.out.println("\n-------Sorted list (Case-Sensitive)-------");
    Arrays.sort(inputList, String.CASE_INSENSITIVE_ORDER);

    // Display the sorted list.
    showList(inputList);
  }

  public static void showList(String[] array) {
    for (String str: array) {
      System.out.print(str + " ");
    }
    System.out.println();
  }
}

Question#3: Write a function to reverse a number in Java.

Ans.

package simple.test;

public class invertNumber {

  public long doInvert(long number) {

    long invert = 0;
    while (number != 0) {
      invert = (invert * 10) + (number % 10);
      number = number / 10;
    }
    return invert;
  }

  public static void main(String args[]) {
    long lnum = 654321;
    invertNumber input = new invertNumber();

    System.out.println("Input value : " + lnum);
    System.out.println("Inverted value : " + input.doInvert(lnum));
  }
}

Question#4: Write a method to check prime no. in Java.

Ans.

package simple.test;

import java.util.Scanner;

public class findPrime {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter an int value : ");
    int input = scan.nextInt();
    if (checkPrime(input)) {
      System.out.println("Input value " + input + " is a prime number.");
    } else {
      System.out.println("Input value " + input +
        " is not a prime number.");
    }
  }

  public static boolean checkPrime(int n) {
    if (n <= 1) {
      return false;
    }
    for (int i = 2; i < Math.sqrt(n); i++) {
      if (n % i == 0) {
        return false;
      }
    }
    return true;
  }
}

Prime number-related Java coding questions are a good way to test candidates’ knowledge of basic algorithms and data structures. For example, a common question is to find the largest prime number less than or equal to a given number. This question can be solved using various algorithms, such as the Sieve of Eratosthenes or the Miller-Rabin test.

By solving prime number-related Java coding questions, candidates can show that they can:

  • Think algorithmically
  • Write efficient code
  • Use data structures effectively

In addition, these questions can also be used to assess candidates’ problem-solving skills and their ability to handle complex problems.

Question#5: Write a Java program to find out the first two max values from an array.

Ans.

package simple.test;

public class findTwoMaxValue {
  public void GetTwoMaxValues(int[] nums) {

    int maxOne = 0;
    int maxTwo = 0;
    for (int n: nums) {
      if (maxOne < n) {
        maxTwo = maxOne;
        maxOne = n;
      } else if (maxTwo < n) {
        maxTwo = n;
      }
    }

    System.out.println("Max1 - " + maxOne);
    System.out.println("Max2 - " + maxTwo);
  }

  public static void main(String[] args) {

    int list[] = {
      15, 24, 48, 21,
      43, 11, 79, 93
    };

    findTwoMaxValue max = new findTwoMaxValue();
    max.GetTwoMaxValues(list);
  }
}

Here is another set of 5 more special Java coding questions for testers…

5 more questions to acquaint testers.

Learning programming is a step towards turning QA engineers into SDET i.e. Software Development Engineers in Test. The Giant, Microsoft was the first IT company to invent a profile like SDET, later many other companies followed it. Let’s come back to the topic of the day. Companies ask coding-related questions to test the programming skills of a tester. It’s the point where the below list of Java coding questions will help you. Since Java is the first choice to do Selenium automation, these questions are a must for the Selenium Webdriver automation testers.

Question#6: Write a Java program to find the longest substring from a given string that doesn’t contain any duplicate characters.

Ans.

package simple.test;

import java.util.HashSet;
import java.util.Set;

public class findSubstr {

  private Set < String > stringSet = new HashSet < String > ();
  private int lstringSet = 0;

  public Set < String > findStr(String input) {

    // Reset instance data.
    stringSet.clear();
    lstringSet = 0;

    // Set a boolean flag on each char's 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 stringSet;
  }

  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() > lstringSet) {
      lstringSet = subStr.length();
      stringSet.clear();
      stringSet.add(subStr);
    } else if (subStr.length() == lstringSet) {
      stringSet.add(subStr);
    }

    return sb.toString();
  }

  public static void main(String a[]) {

    findSubstr substr = new findSubstr();

    System.out
      .println("Actual Strings ------------ | ---- Longest Non-Repeated Strings");
    System.out.println("Software_Programmer" +
      "         |         " + substr.findStr("Software_Programmer"));
    System.out.println("Software_Developer_In_Test" +
      "  |         " + substr.findStr("Software_Developer_In_Test"));
    System.out.println("developers_write_unit_tests" +
      " |         " + substr.findStr("developers_write_unit_tests"));
    System.out.println("javajavbasp.net" +
      "             |         " + substr.findStr("javajavbasp.net"));
  }
}

Question#7: Write Java code to get rid of multiple spaces from a string.

Ans.

package simple.test;

import java.util.StringTokenizer;

public class removeExtraSpaces {

  public static void main(String args[]) {

    String input = "Try    to    remove   extra   spaces.";
    StringTokenizer substr = new StringTokenizer(input, " ");
    StringBuffer sb = new StringBuffer();

    while (substr.hasMoreElements()) {
      sb.append(substr.nextElement()).append(" ");
    }

    System.out.println("Actual string: " + input);
    System.out.println("Processed string: " + sb.toString().trim());
  }
}

Question#8: Write Java code to identify a number as Palindrome.

Ans.

package simple.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class identifyPalindrome {

  public static void main(String[] args) {

    try {
      BufferedReader object = new BufferedReader(new InputStreamReader(
        System.in));
      System.out.println("Input number");
      int inputValue = Integer.parseInt(object.readLine());
      int n = inputValue;
      int rev = 0;
      System.out.println("Input value is : ");
      System.out.println(" " + inputValue);
      for (int i = 0; i <= inputValue; i++) {
        int r = inputValue % 10;
        inputValue = inputValue / 10;
        rev = rev * 10 + r;
        i = 0;
      }
      System.out.println("Post reversal : " + " ");
      System.out.println(" " + rev);
      if (n == rev) {
        System.out.print("Input value is a palindrome.");
      } else {
        System.out.println("Input value is not a palindrome.");
      }
    } catch (Exception e) {
      System.out.println("Out of Range.");
    }
  }
}

Question#9: Write Java code to swap two numbers without using a temporary variable.

Ans.

package simple.test;

public class smartSwapping {

  public static void main(String args[]) {

    int numX = 10;
    int numY = 20;
    System.out.println("Pre-swapping state:");
    System.out.println("numX value: " + numX);
    System.out.println("numY value: " + numY);

    System.out.println("");

    numX = numX + numY;
    numY = numX - numY;
    numX = numX - numY;
    System.out.println("Post-swapping state:");
    System.out.println("numX value: " + numX);
    System.out.println("numY value: " + numY);
  }
}

Question#10: Write a Java program to demonstrate string reverse with and without the StringBuffer class.

Ans.

package simple.test;

public class invertString {

  public String invertWithStringBuffer(String str) {

    StringBuffer buffer = new StringBuffer(str);
    buffer.reverse();
    return buffer.toString();
  }

  public String invertWithoutStringBuffer(String str) {

    int length = str.length();
    String original = str;
    String invert = "";
    for (int i = length - 1; i >= 0; i--) {
      invert = invert + original.charAt(i);
    }
    return invert;
  }

  public static void main(String[] args) {

    invertString invertStr = new invertString();

    System.out.println("Inverted String with StringBuffer class: " +
      invertStr.invertWithStringBuffer("987654321"));

    System.out.println("");

    System.out.println("Inverted String without StringBuffer class: " +
      invertStr.invertWithoutStringBuffer("kjihgfedcba"));
  }
}

Set-3 of Java Coding Interview Questions for Testers

Because our readers have expressed a strong liking for this post, we are enriching it with five additional Java coding questions in this tutorial. These questions will assess and enhance your logical and data structure knowledge.

Question#11: Code to print the largest prime number in Java as per the below rules.

a) Make sure the prime number is less than or equal to a given number.
b) Ask for user input.

Ans.

import java.util.Scanner;

public class LargestPrime {
    // Check if a number is prime
    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        if (num <= 3) {
            return true;
        }
        if (num % 2 == 0 || num % 3 == 0) {
            return false;
        }
        for (int i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    // Find the largest prime less than or equal to a given number
    public static int findLargestPrime(int n) {
        for (int i = n; i >= 2; i--) {
            if (isPrime(i)) {
                return i;
            }
        }
        return -1; // No prime found (shouldn't occur for n >= 2)
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        scanner.close();

        int largestPrime = findLargestPrime(number);

        if (largestPrime != -1) {
            System.out.println("The largest prime less than or equal to " + number + " is: " + largestPrime);
        } else {
            System.out.println("No prime found less than or equal to " + number);
        }
    }
}

Once you compile and run the above code, it asks for user input and calculates the largest prime.

Enter a number: 50
The largest prime less than or equal to 50 is: 47

Question#12: Implement a linked list using Java code following the below rules:

a) Add a node to the beginning of the list.
b) Add a node to the end of the list.
c) Remove a node from the beginning of the list.
d) Remove a node from the end of the list.
e) Check if the list is empty.

Ans.

public class MyLinkedList {
    private class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
            next = null;
        }
    }

    private ListNode head;
    private ListNode tail;

    public MyLinkedList() {
        head = null;
        tail = null;
    }

    // Add a node to the beginning of the list
    public void addToFront(int val) {
        ListNode newNode = new ListNode(val);
        if (isEmpty()) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.next = head;
            head = newNode;
        }
    }

    // Add a node to the end of the list
    public void addToEnd(int val) {
        ListNode newNode = new ListNode(val);
        if (isEmpty()) {
            head = newNode;
            tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
    }

    // Remove a node from the beginning of the list
    public void removeFromFront() {
        if (!isEmpty()) {
            head = head.next;
        }
    }

    // Remove a node from the end of the list
    public void removeFromEnd() {
        if (!isEmpty()) {
            if (head == tail) {
                head = null;
                tail = null;
            } else {
                ListNode current = head;
                while (current.next != tail) {
                    current = current.next;
                }
                current.next = null;
                tail = current;
            }
        }
    }

    // Check if the list is empty
    public boolean isEmpty() {
        return head == null;
    }

    // Print the elements in the list in a formatted way
    public void printList() {
        if (isEmpty()) {
            System.out.println("The list is empty.");
            return;
        }
    
        ListNode current = head;
        System.out.print("List: ");
        while (current != null) {
            System.out.print(current.val);
            if (current.next != null) {
                System.out.print(" -> ");
            }
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        
        list.addToFront(2);
        list.addToFront(1);
        list.addToEnd(3);
        list.addToEnd(4);
        
        list.printList(); // Output: List: 1 -> 2 -> 3 -> 4
        
        list.removeFromFront();
        list.removeFromEnd();
        
        list.printList(); // Output: List: 2 -> 3
    }
}

The above will print the link lists that were created during execution. It will show the following result:

List: 1 -> 2 -> 3 -> 4
List: 2 -> 3

Data structure Java coding questions are ideal for interview preparation because they assess your problem-solving skills, programming knowledge, and coding skills.

To answer these questions, you must devise creative and efficient solutions to complex problems, demonstrate your understanding of essential programming concepts, and write clean, efficient, and bug-free code.

By practicing these questions, you can improve your chances of success in your Java interview.

Question#13: Code a binary search tree in Java following the below rules:

a) Insert a node into the tree.
b) Search for a node in the tree.
c) Delete a node from the tree.

Ans.

public class MyBinarySearchTree {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
            left = null;
            right = null;
        }
    }

    private TreeNode root;

    public MyBinarySearchTree() {
        root = null;
    }

    // Insert a node into the BST
    public void insert(int val) {
        root = insertRecursive(root, val);
    }

    private TreeNode insertRecursive(TreeNode current, int val) {
        if (current == null) {
            return new TreeNode(val);
        }

        if (val < current.val) {
            current.left = insertRecursive(current.left, val);
        } else if (val > current.val) {
            current.right = insertRecursive(current.right, val);
        }

        return current;
    }

    // Search for a node in the BST
    public boolean contains(int val) {
        return searchRecursive(root, val);
    }

    private boolean searchRecursive(TreeNode current, int val) {
        if (current == null) {
            return false;
        }

        if (val == current.val) {
            return true;
        }

        if (val < current.val) {
            return searchRecursive(current.left, val);
        } else {
            return searchRecursive(current.right, val);
        }
    }

    // Delete a node from the BST
    public void remove(int val) {
        root = deleteRecursive(root, val);
    }

    private TreeNode deleteRecursive(TreeNode current, int val) {
        if (current == null) {
            return null;
        }

        if (val == current.val) {
            // Node with only one child or no child
            if (current.left == null) {
                return current.right;
            } else if (current.right == null) {
                return current.left;
            }

            // Node with two children, get the in-order successor (smallest in the right subtree)
            current.val = findMinValue(current.right);

            // Delete the in-order successor
            current.right = deleteRecursive(current.right, current.val);
        } else if (val < current.val) {
            current.left = deleteRecursive(current.left, val);
        } else {
            current.right = deleteRecursive(current.right, val);
        }

        return current;
    }

    private int findMinValue(TreeNode node) {
        int minValue = node.val;
        while (node.left != null) {
            minValue = node.left.val;
            node = node.left;
        }
        return minValue;
    }

    public static void main(String[] args) {
        MyBinarySearchTree bst = new MyBinarySearchTree();
        bst.insert(50);
        bst.insert(30);
        bst.insert(70);
        bst.insert(20);
        bst.insert(40);
        bst.insert(60);
        bst.insert(80);

        System.out.println("Contains 40: " + bst.contains(40)); // Should return true
        System.out.println("Contains 90: " + bst.contains(90)); // Should return false

        bst.remove(30); // Delete a node with one child
        bst.remove(70); // Delete a node with two children

        System.out.println("Contains 30 after deletion: " + bst.contains(30)); // Should return false
        System.out.println("Contains 70 after deletion: " + bst.contains(70)); // Should return false
    }
}

As you compile the above Java code and run it, you’ll receive the following output:

Contains 40: true
Contains 90: false
Contains 30 after deletion: false
Contains 70 after deletion: false

Question#14: Code a hash table in Java as per the following rules:

a) Put a key-value pair into the hash table.
b) Get a value from the hash table for a given key.
c) Remove a key-value pair from the hash table for a given key.

Ans.

public class MyHashTable<K, V> {
    private Entry<K, V>[] entries;
    private int capacity;
    private static final int DEFAULT_CAPACITY = 10;

    public MyHashTable() {
        this(DEFAULT_CAPACITY);
    }

    public MyHashTable(int capacity) {
        this.capacity = capacity;
        entries = new Entry[capacity];
    }

    public void put(K key, V value) {
        int index = calculateHash(key);
        Entry<K, V> entry = new Entry<>(key, value);

        if (entries[index] == null) {
            entries[index] = entry;
        } else {
            // Handle collision
            Entry<K, V> currentEntry = entries[index];
            while (currentEntry.next != null) {
                currentEntry = currentEntry.next;
            }
            currentEntry.next = entry;
        }
    }

    public V get(K key) {
        int index = calculateHash(key);
        Entry<K, V> entry = entries[index];

        while (entry != null) {
            if (entry.key.equals(key)) {
                return entry.value;
            }
            entry = entry.next;
        }

        return null;
    }

    public void remove(K key) {
        int index = calculateHash(key);
        Entry<K, V> entry = entries[index];
        Entry<K, V> previousEntry = null;

        while (entry != null) {
            if (entry.key.equals(key)) {
                if (previousEntry == null) {
                    entries[index] = entry.next;
                } else {
                    previousEntry.next = entry.next;
                }
                return;
            }
            previousEntry = entry;
            entry = entry.next;
        }
    }

    private int calculateHash(K key) {
        // Implement a hash function here, for example:
        return Math.abs(key.hashCode() % capacity);
    }

    private static class Entry<K, V> {
        K key;
        V value;
        Entry<K, V> next;

        public Entry(K key, V value) {
            this.key = key;
            this.value = value;
            this.next = null;
        }
    }

    public static void main(String[] args) {
        // Example of how to use the MyHashTable class
        MyHashTable<String, Integer> table = new MyHashTable<>();
    
        // Insert some key-value pairs
        table.put("Alice", 25);
        table.put("Bob", 30);
        table.put("Charlie", 22);
        table.put("David", 28);
    
        // Retrieve and print values
        System.out.println("Age of Alice: " + table.get("Alice"));
        System.out.println("Age of Bob: " + table.get("Bob"));
        System.out.println("Age of Charlie: " + table.get("Charlie"));
        System.out.println("Age of David: " + table.get("David"));
    
        // Remove an entry
        table.remove("Bob");
    
        // Check if Bob's age is still available
        Integer bobAge = table.get("Bob");
        if (bobAge == null) {
            System.out.println("Bob's age is not found (Bob was removed).");
        } else {
            System.out.println("Age of Bob: " + bobAge);
        }
    
        // Add more data
        table.put("Eva", 35);
        table.put("Frank", 40);
        table.put("Grace", 19);
    
        // Print all ages
        System.out.println("Age of Eva: " + table.get("Eva"));
        System.out.println("Age of Frank: " + table.get("Frank"));
        System.out.println("Age of Grace: " + table.get("Grace"));
        
        // You can perform other operations on the hash table here
    }
}

Once you compile and run the above code, it will give the following result:

Age of Alice: 25
Age of Bob: 30
Age of Charlie: 22
Age of David: 28
Bob's age is not found (Bob was removed).
Age of Eva: 35
Age of Frank: 40
Age of Grace: 19

Question#15: Write a program to find the minimum spanning tree (MST) of a graph.

A minimum spanning tree is a subset of the graph’s edges that connects all of the graph’s vertices, without any cycles and has the lowest total weight.

Ans.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class E {
    int src, dest, weight;

    public E(int src, int dest, int weight) {
        this.src = src;
        this.dest = dest;
        this.weight = weight;
    }
}

class G {
    int v, e;
    E[] edges;

    public G(int v, int e) {
        this.v = v;
        this.e = e;
        edges = new E[e];
    }

    public void addEdge(int src, int dest, int weight, int idx) {
        edges[idx] = new E(src, dest, weight);
    }

    public List<E> findMST() {
        Arrays.sort(edges, Comparator.comparingInt(edge -> edge.weight));
        List<E> mst = new ArrayList<>();
        int[] parent = new int[v];

        for (int i = 0; i < v; i++) {
            parent[i] = i;
        }

        int edgeCount = 0;
        int i = 0;

        while (edgeCount < v - 1 && i < e) {
            E edge = edges[i++];
            int srcRoot = find(parent, edge.src);
            int destRoot = find(parent, edge.dest);

            if (srcRoot != destRoot) {
                mst.add(edge);
                union(parent, srcRoot, destRoot);
                edgeCount++;
            }
        }

        return mst;
    }

    private int find(int[] parent, int vertex) {
        if (parent[vertex] != vertex) {
            parent[vertex] = find(parent, parent[vertex]);
        }
        return parent[vertex];
    }

    private void union(int[] parent, int x, int y) {
        int xRoot = find(parent, x);
        int yRoot = find(parent, y);
        parent[xRoot] = yRoot;
    }
}

public class MST {
    public static void main(String[] args) {
        int v = 6;
        int e = 9;

        G test = new G(v, e);
        test.addEdge(0, 1, 4, 0);
        test.addEdge(0, 2, 3, 1);
        test.addEdge(1, 2, 2, 2);
        test.addEdge(1, 3, 1, 3);
        test.addEdge(2, 3, 5, 4);
        test.addEdge(2, 4, 6, 5);
        test.addEdge(3, 4, 7, 6);
        test.addEdge(3, 5, 8, 7);
        test.addEdge(4, 5, 9, 8);

        List<E> mst = test.findMST();

        System.out.println("Minimum Spanning Tree (MST):");
        System.out.println("Edge   Source - Destination   Weight");
        for (E edge : mst) {
            System.out.println(edge.src + "  -  " + edge.dest + "  :  " + edge.weight);
        }
    }
}

In the above code, we have assumed certain values for the edges and vertices. However, you may change them as deemed fit for you. Once you compile and run it, it brings you the following output.

Minimum Spanning Tree (MST):
Edge   Source - Destination   Weight
1  -  3  :  1
1  -  2  :  2
0  -  2  :  3
2  -  4  :  6
3  -  5  :  8

If you recently gave a Selenium Webdriver interview and faced similar or different Java coding questions. Then, please write to us and help us increase our interview question bank. It’ll be a great help not only for us but for the other readers of this blog. We’ll surely add your submissions to our list of Java coding questions. And, you’ll get a direct mention on our blog. By the way, if you have not already gone through it, do check out our top post on the top 30 Java coding questions for programmers.

Conclusion

Java programming language is one of the prerequisites for Selenium Webdriver automation. It supports many languages like Python, C#, Ruby, and Perl. Though, our principal goal is to make you self-sufficient in Java and Python programming. So, you can use these skills in different conditions be it for automation testing or software development. Because of these obvious reasons, we delivered this set of top 15 Java coding questions for testers.

All the Best,

TechBeamers.

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:Java Coding TipsJava Questions Answers

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Why Should You Run Selenium Tests in Cloud How to Run Selenium Tests in the Cloud
Next Article Amazon Quality Assurance Engineer Interview Guide How to Prepare for the Amazon QA Engineer Interview?

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x