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


February 25, 2024

Java Problems Solutions: Add two numbers without using the plus operator in Java


public class AddWithoutPlus {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 5;
        int sum = add(num1, num2);
        System.out.print("Sum: ");
        System.out.println(sum);        
    }
    public static int add(int a, int b) {
        while (b != 0) {
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        return a;
    }
}

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

:

February 03, 2024

Java Problems Solutions: Java Remove Unwanted Characters from String


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringCleaner {
    public static void main(String[] args) {
        String inputString = "Hello#123, Software Testing Space !Sub@scriber!";
        String cleanedString = removeUnwantedCharacters(inputString);
        System.out.println("Original String: " + inputString);
        System.out.println("Cleaned String: " + cleanedString);
    }
    // Java method to remove unwanted characters from a string
    public static String removeUnwantedCharacters(String input) {
        // Keep only alphabets and whitespace.
        // Define a regular expression.
        String regex = "[^a-zA-Z\\s]";
        // Compile the pattern and create a matcher with the input string.
        Matcher matcher = Pattern.compile(regex).matcher(input);
        // Replace unwanted characters with an empty string
        return matcher.replaceAll("");
    }
}

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

:


January 29, 2024

Java Array: Largest, Smallest, Search, Sort, Find Duplicates


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

public class ArrayHandler {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 9, 1, 5, 7, 2, 1, 8, 4, 6, 1};
        System.out.println("Find largest and smallest in an array:");
        findLargestAndSmallest(numbers);
       System.out.println("\nSearch element in an array:");
        int target = 17;
        System.out.println("Is " + target + " present? " + searchElement(numbers, target));
        System.out.println("\nSort elements in an array:");
        sortArray(numbers);
        System.out.println("\nHow to find duplicates in an array or list:");
        findDuplicates(numbers);
    }
    // Find largest and smallest in an array
    public static void findLargestAndSmallest(int[] array) {
        Arrays.sort(array);
        int smallest = array[0];
        int largest = array[array.length - 1];
        System.out.println("Smallest: " + smallest);
        System.out.println("Largest: " + largest);
    }
    // Search element in an array
    public static boolean searchElement(int[] array, int target) {
        for (int num : array) {
            if (num == target) {
                return true;
            }
        }
        return false;
    }
    // Sort elements in an array
    public static void sortArray(int[] array) {
        Arrays.sort(array);
        System.out.println("Sorted Array: " + Arrays.toString(array));
    }
    // How to find duplicates in an array or list
    public static void findDuplicates(int[] array) {
    	// A Set is a collection that does not allow duplicate elements. 
    	Set uniqueSet = new HashSet<>();
        Set duplicates = new HashSet<>();

        for (int num : array) {
            // If the element's already present, uniqueSet.add(num) returns false, meaning that it's a duplicate.
        	if (!uniqueSet.add(num)) {
                duplicates.add(num);
            }
        }
        System.out.println("Duplicate elements: " + duplicates);
    }

}

Want 1 to 1 personalized Java training? Email me at isingh30@gmail.com please.

January 26, 2024

Java Problems Solutions: Check if a String is a Palindrome


public class CheckPalindrome {
    public static void main(String[] args) {
    	String inputString = "Was it a car or a cat I saw?";
        // Check if the input string is a palindrome.
        if (isPalindrome(inputString)) {
            System.out.println("The given string is a palindrome.");
        } else {
            System.out.println("The given string is not a palindrome.");
        }
    }
    // Function to check if a string is a palindrome
    public static boolean isPalindrome(String str) {
        // Remove spaces and convert to lower case for case-insensitive comparison.
    	str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int left = 0;
        int right = str.length() - 1;
        // Check characters from both ends towards the center
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false; // Characters do not match, so its not a palindrome.
            }
            left++;
            right--;
        }
        return true; // All characters matched, so its a palindrome.
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please.


January 23, 2024

Java Problems Solutions: Generate Fibonacci series


public class FibonacciGenerator {
   public static void main(String[] args) {
       int numberMembers = 10; // Set the limit for the Fibonacci series
       generateFibonacci(numberMembers); // Generate and print the Fibonacci series
   }

   // Function to generate Fibonacci series up to a given limit
   public static void generateFibonacci(int limit) {
       // Check if the limit is less than or equal to 0
       if (limit <= 1) {
           System.out.println("Please provide a valid number of members greater than 1.");
           return;
       }

       // Initialize the first two numbers in the series
       int num1 = 0, num2 = 1;

       // Print the first two numbers
       System.out.print("Fibonacci series up to " + limit + " members: " + num1 + ", " + num2);

       // Generate the Fibonacci series
       for (int i = 1; i < limit-1; i++) {
           int nextNum = num1 + num2;
           // Print the next number
           System.out.print(", " + nextNum);
           // Update num1 and num2 for the next iteration
           num1 = num2;
           num2 = nextNum;
       }
   }
}

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

:


January 22, 2024

Java Problems Solutions: Reverse a String and Check if a string is a palindrome


import java.util.Scanner;

public class StringReverser {
    public static void main(String[] args) {
        // Get input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String inputString = scanner.nextLine();
        scanner.close();

        // Step 2: Reverse the string
        String reversedString = reverseString(inputString);

        // Step 3: Display the reversed string
        System.out.println("The reversed string is: " + reversedString);

        // Step 4: Compare strings
        compareStrings(inputString, reversedString);
    }

    // Function to reverse a string
    private static String reverseString(String original) {
        StringBuilder reversed = new StringBuilder();
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed.append(original.charAt(i));
        }
        return reversed.toString();
    }

    // Function to compare two strings
    private static void compareStrings(String str1, String str2) {
        // 1st way: Using equals() method (exact equality)
        boolean isEqual1 = str1.equals(str2);
        System.out.println("Using equals() method: Strings are equal? " + isEqual1);

        // 2nd way: Using equalsIgnoreCase() method
        boolean isEqual2 = str1.equalsIgnoreCase(str2);
        System.out.println("Using equalsIgnoreCase() method: Strings are equal? " + isEqual2);

        // 3rd way: Using compareTo() method
        int comparisonResult = str1.compareTo(str2);
        System.out.println("Using compareTo() method: Comparison result: " + comparisonResult);
    }
}

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

: