March 26, 2024

Advanced Java Problems

Advanced Java problems for QA Automation Tester interviews

The list starts simple and moves to more complex topics such as data structures and algorithms. These problems in increasing order of difficulty are as follows:

  1. Check if a year is a leap year
  2. Find the missing number in an array of 1 to N
  3. Find the common elements between two arrays
  4. Count the number of vowels and consonants in a string
  5. Calculate the length of a string without using the length() method
  6. Swap two numbers without using a temporary variable
  7. Calculate the power of a number without using the Math class
  8. Calculate the square root of a number without using the Math class
  9. Calculate the area of a circle
  10. Find the intersection of two arrays
  11. Find the second largest element in an array
  12. Calculate the average of an array of numbers
  13. Implement a binary search algorithm
  14. Implement a bubble sort algorithm
  15. Implement a selection sort algorithm
  16. Implement an insertion sort algorithm
  17. Implement a quicksort algorithm
  18. Implement a factorial function using recursion
  19. Implement a Linked List
  20. Find the reverse of this linked list
  21. Remove duplicates from a sorted linked list
  22. Check if two strings are anagrams
  23. Convert a string to an integer
  24. Convert an integer to a string
  25. Calculate the GCD (Greatest Common Divisor) of two numbers
  26. Check if a number is a perfect square
  27. Implement a HashMap in Java
  28. Implement a HashSet in Java

March 13, 2024

Java Problem Solution: Implement a Linked List in Java


public class LinkedList {
    public static void main(String[] args) {
        // Test LinkedList
        Node head = createSampleList();
        System.out.print("Original Linked List: ");
        printLinkedList(head);

        int newData = 123; // Insert new node anywhere
        head = insertAnywhere(head, newData, 2);
        System.out.println("Linked List after inserting " + newData + " at position 5: ");
        printLinkedList(head);

        int dataToDelete = 4; // Delete node with data 4
        head = deleteNode(head, dataToDelete);
        System.out.println("Linked List after deleting node with data " + dataToDelete + ": ");
        printLinkedList(head);
    }
    static class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    // Function to create a sample LinkedList
    private static Node createSampleList() {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        return head;
    }
    // Function to print the elements of a LinkedList
    private static void printLinkedList(Node head) {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    // Function to insert a new node at any position in the LinkedList
    private static Node insertAnywhere(Node head, int newData, int position) {
        Node newNode = new Node(newData);
        if (head == null || position <= 0) {
            newNode.next = head;
            return newNode;
        }
        Node current = head;
        for (int i = 0; i < position - 1 && current.next != null; i++) {
            current = current.next;
        }
        newNode.next = current.next;
        current.next = newNode;
        return head;
    }
    // Function to delete a node with a given data value from the LinkedList
    private static Node deleteNode(Node head, int dataToDelete) {
        if (head == null) {
            return null;
        }
        if (head.data == dataToDelete) {
            return head.next;
        }
        Node current = head;
        while (current.next != null) {
            if (current.next.data == dataToDelete) {
                current.next = current.next.next;
                return head;
            }
            current = current.next;
        }
        return head;
    }
}

March 12, 2024

Java Problem Solution: Find the Intersection of two Arrays in Java


import java.util.Arrays;
public class ArrayIntersection {
    public static void main(String[] args) {
        int[] arr1 = {1, 8, 3, 4, 5};
        int[] arr2 = {4, 5, 6, 7, 8, 5, 1};
        int[] intersection = findIntersection(arr1, arr2);
        System.out.print("Intersection of arrays: ");
        for (int num : intersection) {
            System.out.print(num + " ");
        }
    }
    public static int[] findIntersection(int[] arr1, int[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        int minLength = Math.min(len1, len2);
        int maxLength = Math.max(len1, len2);
        int[] result = new int[minLength];
        int index = 0;
        // Determine the smaller and larger arrays
        int[] smallerArray = (len1 <= len2) ? arr1 : arr2;
        int[] largerArray = (len1 > len2) ? arr1 : arr2;
        for (int num : smallerArray) {
            if (contains(num, largerArray)) {
                result[index++] = num;
            }
        }
        return Arrays.copyOf(result, index);
    }
    public static boolean contains(int value, int[] arr) {
        for (int num : arr) {
            if (num == value) {
                return true;
            }
        }
        return false;
    }
}

March 11, 2024

Java Problem Solution: Check if a Number is Prime or Not in Java


public class PrimeChecker {
    public static void main(String[] args) {
        int numberToCheck = 4; // Change this to test different numbers.
        if (isPrime(numberToCheck)) {
            System.out.println(numberToCheck + " is a prime number.");
        } else {
            System.out.println(numberToCheck + " is not a prime number.");
        }
    }
    // A prime number is a natural number greater than 1 that has no positive divisors
    // other than 1 and itself.
    public static boolean isPrime(int number) {
    	//return true if the number is prime, false otherwise.
    	if (number <= 1) {
            return false; // Numbers less than or equal to 1 are not prime
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false; // If number is divisible by any other number, it's not prime
            }
        }
        return true; // If the loop completes without finding divisors, number is prime
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

March 10, 2024

Java Problem Solution: Calculate the Factorial of a Number in Java (Loop and Recursion)


public class FactorialCalculator {
    public static void main(String[] args) {
        int numberToCalculate = 5; // Change this to test different numbers.
        try {
            long factorialWithLoop = calculateFactorialWithLoop(numberToCalculate);
            System.out.println("Factorial of " + numberToCalculate + " using loop: " + factorialWithLoop);
            long factorialWithRecursion = calculateFactorialWithRecursion(numberToCalculate);
            System.out.println("Factorial of " + numberToCalculate + " using recursion: " + factorialWithRecursion);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
    public static long calculateFactorialWithLoop(int number) {
    	// Time complexity O(n)
        if (number < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
        }
        long factorial = 1;
        for (int i = 2; i <= number; i++) {
            factorial *= i;
        }
        return factorial;
    }
    
    public static long calculateFactorialWithRecursion(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
        }
        if (number == 0 || number == 1) {
            return 1;
        }
    	// Time complexity O(n)        
        return number * calculateFactorialWithRecursion(number - 1);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

March 08, 2024

Java Problem Solution: Convert a Decimal to Binary in Java and Convert a Binary to Decimal in Java


public class DecimalBinaryConversion {
    public static void main(String[] args) {
    	// Enter positive decimal or binary values only.
    	int decimal = 15;
        System.out.println("Decimal to Binary:");
        System.out.println("Decimal " + decimal + " -> Binary: " + decimalToBinary(decimal));
        String binary = "1110";
        System.out.println("\nBinary to Decimal:");
        System.out.println("Binary " + binary + " -> Decimal: " + binaryToDecimal(binary));
    }
    // Function to convert decimal to binary
    public static String decimalToBinary(int decimal) {
        StringBuilder binary = new StringBuilder();
        while (decimal > 0) {
            binary.insert(0, decimal % 2);
            decimal /= 2;
        }
        return binary.toString();
    }
    // Function to convert binary to decimal
    public static int binaryToDecimal(String binary) {
        int decimal = 0;
        int power = 0;
        for (int i = binary.length() - 1; i >= 0; i--) {
            if (binary.charAt(i) == '1') {
                decimal += Math.pow(2, power);
            }
            power++;
        }
        return decimal;
    }
}

March 07, 2024

Java Problem Solution: Count Occurrences of a Character in a String Java


public class CharacterCounter {
    public static void main(String[] args) {
        String str = "Hello, Software and Testing Training Subscriber!";
        char targetChar = 'r';
        System.out.println("String: " + str);
        System.out.println("Character to count: " + targetChar);
        System.out.println("Occurrences: " + countOccurrences(str, targetChar));
    }
    // Count occurrences of a character in a string java, 
    // Considering the character's case
    public static int countOccurrences(String str, char targetChar) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == targetChar) {
                count++;
            }
        }
        return count;
    }
}

March 06, 2024

Java Problem Solution: Find the Sum of Digits of a number in Java


public class DigitSumCalculator {
    public static void main(String[] args) {
        int number = 1234;
        System.out.println("Number: " + number);
        System.out.println("Sum of digits: " + calculateDigitSum(number));
    }

    // Function to find the sum of digits of a number in Java
    public static int calculateDigitSum(int number) {
        int sum = 0;
        while (number != 0) {
            sum += number % 10; // Add the last digit to the sum
            number /= 10; // Remove the last digit from the number
        }
        return sum;
    }
}

March 05, 2024

Java Problems Solutions: Implement a Queue in Java


public class MyQueue {
    private int maxSize; // Maximum size of the queue
    private String[] queueArray; // Array to hold the queue elements
    private int front; // Index of the front element in the queue
    private int rear; // Index of the rear element in the queue
    private int currentSize; // Current size of the queue

    public static void main(String[] args) {// Test the queue
        MyQueue queue = new MyQueue(3); // Set max size to 3
        queue.enqueue("A");
        queue.enqueue("B");
        queue.enqueue("C");
        queue.enqueue("D"); // Attempt to enqueue into a full queue
        
        System.out.println("Is the queue full? " + queue.isFull());
        
        System.out.println("Front element: " + queue.peek());
        System.out.println("Dequeue: " + queue.dequeue());
        System.out.println("Front element after dequeue: " + queue.peek());
        
        queue.dequeue();queue.dequeue();
        System.out.println("Is the queue empty? " + queue.isEmpty());        
        queue.dequeue(); // Attempt to dequeue from an empty queue
    }

    public MyQueue(int size) {// Constructor to initialize the queue with a specified size
        maxSize = size;
        queueArray = new String[maxSize];
        front = 0; // Initialize front as 0
        rear = -1; // Initialize rear as -1
        currentSize = 0; // Initialize currentSize as 0
    }

    public void enqueue(String value) {// Method to enqueue an element into the queue
        if (!isFull()) {
            rear = (rear + 1) % maxSize;
            queueArray[rear] = value;
            currentSize++;
        } else {
            System.out.println("Cannot enqueue. Queue is full.");
        }
    }

    public String dequeue() {// Method to dequeue an element from the queue
        if (!isEmpty()) {
            String removedItem = queueArray[front];
            front = (front + 1) % maxSize;
            currentSize--;
            return removedItem;
        } else {
            System.out.println("Cannot dequeue. Queue is empty.");
            return null;
        }
    }

    public String peek() {// Method to get the front element of the queue without removing it
        if (!isEmpty()) {
            return queueArray[front];
        } else {
            System.out.println("Queue is empty.");
            return null;
        }
    }

    public boolean isEmpty() {// Method to check if the queue is empty
        return currentSize == 0;
    }

    public boolean isFull() {// Method to check if the queue is full
        return currentSize == maxSize;
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

March 04, 2024

Java Problems Solutions: Implement a Stack in Java


public class MyStack {
/* A stack is a data structure that follows the Last In First Out (LIFO) principle,
meaning the last element added to the stack will be the first one to be removed.*/
    private int maxSize; // Maximum size of the stack
    private String[] stackArray; // Array to hold the stack elements
    private int top; // Index of the top element in the stack

    public static void main(String[] args) {// Test the stack
    	MyStack s = new MyStack(3);
    	s.push("A");
    	s.push("B");
    	s.push("C");
    	System.out.println(s.isFull() ? "Stack full" : "Stack not full");
    	if (!s.isFull()) {
            s.push("D");
        } else {
            System.out.println("Cannot push onto a full stack.");
        }
    	System.out.println("Output: " + s.pop()); // Should output the last element
        System.out.println("Output: " + s.pop()); // Should output the last element     
        System.out.println("Output: " + s.pop()); // Should output the last element
        System.out.println(s.isEmpty() ? "Stack empty" : "Stack not empty");   
    	if (!s.isEmpty()) {
            s.pop();
        } else {
            System.out.println("Cannot pop from an empty stack.");
        }
    }
    
    public MyStack(int size) {// Constructor to initialize the stack with a specified size
        maxSize = size;
        stackArray = new String[maxSize];
        top = -1; // Initialize top as -1 indicating an empty stack
    }

    public void push(String value) {// Method to push an element onto the stack
        // Increment top and add the element to the stack
        stackArray[++top] = value;
    }

    public String pop() {// Method to pop an element from the stack
        // Retrieve the element at the top and decrement top
        return stackArray[top--];
    }

    public boolean isEmpty() {// Method to check if the stack is empty
        return (top == -1);
    }

    public boolean isFull() {// Method to check if the stack is full
        return (top == maxSize - 1);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video


March 03, 2024

Java Problems Solutions: How to Reverse each Word in a String in Java


public class ReverseWordsInString {
    public static void main(String[] args) {
        String input = "Follow me in LinkedIn";
        String output = combineWords(input);
        System.out.println("Input: " + input);
        System.out.println("Output: " + output);
    }
	// Function to create the output String
    public static String combineWords(String str) {
        // Split the string into words
        String[] words = str.split(" ");
        StringBuilder outputString = new StringBuilder();
        // Iterate through each word
        for (String word : words) {
            // Reverse the word and append it to the result
            String reversedWord = reverseWord(word);
            outputString.append(reversedWord).append(" ");
        }
        // Convert StringBuilder to String and remove trailing space
        return outputString.toString().trim();
    }
    // Function to reverse a word
    private static String reverseWord(String word) {
        char[] wordChars = word.toCharArray();
        int start = 0;
        int end = wordChars.length - 1;
        // Swap characters from start and end until they meet in the middle
        while (start < end) {
            char temp = wordChars[start];
            wordChars[start] = wordChars[end];
            wordChars[end] = temp;
            start++;
            end--;
        }
        // Convert char array back to String
        return new String(wordChars);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video