πŸ”2️⃣5οΈβƒ£βž• Java Programming Interview Questions For Automation Testing 2024 πŸš€

Table of Contents

πŸ€—Introduction

Below are commonly asked Java Programming Interview Questions for Automation Testing:

Write a Java program to check if a given number is prime or not.

				
					public class PrimeChecker {
    public static boolean isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        int number = 17; // Change the number here
        if (isPrime(number)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }
    }
}

				
			

Write a Java program to reverse a string.

				
					public class StringReversal {
    public static String reverseString(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }
    
    public static void main(String[] args) {
        String original = "hello"; // Change the string here
        String reversed = reverseString(original);
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

				
			

Write a Java program to find the factorial of a number.

				
					public class Factorial {
    public static int factorial(int num) {
        if (num == 0 || num == 1) return 1;
        int result = 1;
        for (int i = 2; i <= num; i++) {
            result *= i;
        }
        return result;
    }
    
    public static void main(String[] args) {
        int number = 5; // Change the number here
        System.out.println("Factorial of " + number + " is: " + factorial(number));
    }
}

				
			

Write a Java program to check if two strings are anagrams of each other.

				
					public class AnagramCheck {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length())
            return false;
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        return Arrays.equals(arr1, arr2);
    }
    public static void main(String[] args) {
        String s1 = "listen";
        String s2 = "silent";
        boolean areAnagrams = areAnagrams(s1, s2);
        System.out.println(s1 + " and " + s2 + " are anagrams: " + areAnagrams); // Output: listen and silent are anagrams: true
    }
}

				
			

Write a Java program to find the Fibonacci series up to a given number.

				
					public class FibonacciSeries {
    public static void fibonacci(int n) {
        int a = 0, b = 1;
        System.out.print(a + " " + b + " ");
        for (int i = 2; i < n; i++) {
            int temp = a + b;
            System.out.print(temp + " ");
            a = b;
            b = temp;
        }
    }
    
    public static void main(String[] args) {
        int count = 10; // Change the count here
        System.out.println("Fibonacci series up to " + count + " terms:");
        fibonacci(count);
    }
}

				
			

Write a Java method to check if a given number is an Armstrong number.

				
					public class ArmstrongNumber {
    public static boolean isArmstrong(int num) {
        int originalNum = num;
        int sum = 0;
        while (num != 0) {
            int digit = num % 10;
            sum += Math.pow(digit, 3); // For a 3-digit number
            num /= 10;
        }
        return sum == originalNum;
    }
    public static void main(String[] args) {
        int number = 153;
        boolean isArm = isArmstrong(number);
        System.out.println(number + " is Armstrong: " + isArm); // Output: 153 is Armstrong: true
    }
}

				
			

Write a Java program to find the largest element in an array.

				
					public class LargestElement {
    public static int findLargest(int[] arr) {
        if (arr == null || arr.length == 0) {
            throw new IllegalArgumentException("Array must not be empty or null.");
        }
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
    
    public static void main(String[] args) {
        int[] array = {5, 7, 2, 10, 8}; // Change the array here
        System.out.println("The largest element in the array is: " + findLargest(array));
    }
}

				
			

Write a Java program to calculate the sum of digits of a number.

				
					public class DigitSum {
    public static int calculateDigitSum(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
    
    public static void main(String[] args) {
        int number = 12345; // Change the number here
        System.out.println("Sum of digits of " + number + " is: " + calculateDigitSum(number));
    }
}

				
			

Write a Java program to find the factorial of a number using recursion.

				
					public class RecursiveFactorial {
    public static int factorial(int num) {
        if (num == 0 || num == 1) return 1;
        return num * factorial(num - 1);
    }
    
    public static void main(String[] args) {
        int number = 5; // Change the number here
        System.out.println("Factorial of " + number + " is: " + factorial(number));
    }
}

				
			

Write a Java program to check if a given string is a palindrome or not

				
					public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left++) != str.charAt(right--)) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        String str = "radar"; // Change the string here
        if (isPalindrome(str)) {
            System.out.println(str + " is a palindrome.");
        } else {
            System.out.println(str + " is not a palindrome.");
        }
    }
}

				
			

Write a Java program to find the GCD (Greatest Common Divisor) of two numbers.

				
					public class GCD {
    public static int findGCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    public static void main(String[] args) {
        int num1 = 36; // Change the numbers here
        int num2 = 24;
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + findGCD(num1, num2));
    }
}

				
			

Write a Java program to find the second largest element in an array.

				
					public class SecondLargestElement {
    public static int findSecondLargest(int[] arr) {
        if (arr == null || arr.length < 2) {
            throw new IllegalArgumentException("Array must have at least two elements.");
        }
        int max = arr[0];
        int secondMax = Integer.MIN_VALUE;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                secondMax = max;
                max = arr[i];
            } else if (arr[i] > secondMax && arr[i] != max) {
                secondMax = arr[i];
            }
        }
        return secondMax;
    }
    
    public static void main(String[] args) {
        int[] array = {5, 7, 2, 10, 8}; // Change the array here
        System.out.println("The second largest element in the array is: " + findSecondLargest(array));
    }
}

				
			

Write a Java program to reverse a linked list.

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

public class ReverseLinkedList {
    public static ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode current = head;
        while (current != null) {
            ListNode nextNode = current.next;
            current.next = prev;
            prev = current;
            current = nextNode;
        }
        return prev;
    }
    
    public static void main(String[] args) {
        ListNode head = new ListNode(1); // Change the linked list here
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        
        System.out.println("Original Linked List:");
        printLinkedList(head);
        
        ListNode reversedHead = reverse(head);
        System.out.println("\nReversed Linked List:");
        printLinkedList(reversedHead);
    }
    
    private static void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
    }
}

				
			

Write a Java program to find the missing number in an array of consecutive numbers from 1 to n.

				
					public class MissingNumber {
    public static int findMissingNumber(int[] nums) {
        int n = nums.length + 1;
        int total = (n * (n + 1)) / 2;
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        return total - sum;
    }
    
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 5, 6, 7, 8}; // Change the array here
        System.out.println("The missing number is: " + findMissingNumber(array));
    }
}

				
			

Write a Java program to find all duplicate elements in an array.

				
					import java.util.*;

public class FindDuplicates {
    public static List<Integer> findDuplicates(int[] nums) {
        List<Integer> result = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (!set.add(num)) {
                result.add(num);
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 2, 4, 5, 3}; // Change the array here
        List<Integer> duplicates = findDuplicates(array);
        System.out.println("Duplicate elements in the array are: " + duplicates);
    }
}

				
			

Write a Java program to check if a given number is a perfect number or not.

				
					public class PerfectNumber {
    public static boolean isPerfectNumber(int num) {
        if (num <= 1) return false;
        int sum = 1;
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                sum += i;
                if (i * i != num) {
                    sum += num / i;
                }
            }
        }
        return sum == num;
    }
    
    public static void main(String[] args) {
        int number = 28; // Change the number here
        if (isPerfectNumber(number)) {
            System.out.println(number + " is a perfect number.");
        } else {
            System.out.println(number + " is not a perfect number.");
        }
    }
}

				
			

Write a Java program to find the longest substring without repeating characters.

				
					import java.util.*;

public class LongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        int maxLength = 0;
        Map<Character, Integer> charIndexMap = new HashMap<>();
        int start = 0;
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            if (charIndexMap.containsKey(c)) {
                start = Math.max(start, charIndexMap.get(c) + 1);
            }
            charIndexMap.put(c, end);
            maxLength = Math.max(maxLength, end - start + 1);
        }
        return maxLength;
    }
    
    public static void main(String[] args) {
        String input = "abcabcbb"; // Change the input string here
        System.out.println("Length of the longest substring without repeating characters: " + lengthOfLongestSubstring(input));
    }
}

				
			

Write a Java program to perform a binary search in a sorted array.

				
					public class BinarySearch {
    public static int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
    
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 7, 9, 11, 13}; // Change the sorted array here
        int target = 7; // Change the target value here
        int index = binarySearch(nums, target);
        if (index != -1) {
            System.out.println("Target found at index: " + index);
        } else {
            System.out.println("Target not found in the array.");
        }
    }
}

				
			

Write a Java Program to find the duplicates of in a given String.

				
					import java.util.HashMap;
import java.util.Map;

public class FindDuplicates {
    public static void main(String[] args) {
        String inputString = "hello world";
        findDuplicates(inputString);
    }

    public static void findDuplicates(String inputString) {
        // Create a HashMap to store characters and their frequencies
        Map<Character, Integer> charCountMap = new HashMap<>();

        // Convert the input string to char array
        char[] charArray = inputString.toCharArray();

        // Iterate through each character in the array
        for (char c : charArray) {
            // If the character is already present in the map, increment its count
            if (charCountMap.containsKey(c)) {
                charCountMap.put(c, charCountMap.get(c) + 1);
            } else {
                // If the character is not present, add it to the map with count as 1
                charCountMap.put(c, 1);
            }
        }

        // Iterate through the map and print characters with count > 1
        System.out.println("Duplicate characters in the given string:");
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " : " + entry.getValue());
            }
        }
    }
}

				
			

Write a Java Program to find the longest consecutive occurrence of integers in a given array.

				
					import java.util.Arrays;

public class LongestConsecutiveOccurrence {
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
        findLongestConsecutiveOccurrence(array);
    }

    public static void findLongestConsecutiveOccurrence(int[] array) {
        int maxCount = 1;
        int currentCount = 1;
        int numWithMaxOccurrence = array[0];

        // Iterate through the array starting from the second element
        for (int i = 1; i < array.length; i++) {
            // If current element is same as previous element, increment current count
            if (array[i] == array[i - 1]) {
                currentCount++;
            } else {
                // If current element is different from previous element,
                // reset current count to 1
                currentCount = 1;
            }

            // Update maxCount and numWithMaxOccurrence if required
            if (currentCount > maxCount) {
                maxCount = currentCount;
                numWithMaxOccurrence = array[i];
            }
        }

        // Print the result
        System.out.println("Longest consecutive occurrence: " + numWithMaxOccurrence +
                           " with count: " + maxCount);
    }
}

				
			

Write a Java Program to find the count of each character in the given string.

				
					import java.util.HashMap;
import java.util.Map;

public class CharacterCount {
    public static void main(String[] args) {
        String inputString = "hello world";
        countCharacters(inputString);
    }

    public static void countCharacters(String inputString) {
        // Create a HashMap to store characters and their frequencies
        Map<Character, Integer> charCountMap = new HashMap<>();

        // Convert the input string to char array
        char[] charArray = inputString.toCharArray();

        // Iterate through each character in the array
        for (char c : charArray) {
            // If the character is already present in the map, increment its count
            if (charCountMap.containsKey(c)) {
                charCountMap.put(c, charCountMap.get(c) + 1);
            } else {
                // If the character is not present, add it to the map with count as 1
                charCountMap.put(c, 1);
            }
        }

        // Iterate through the map and print characters with their counts
        System.out.println("Character count in the given string:");
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

				
			

Write a Java program to print a right-angled triangle using stars.

				
					import java.util.Scanner;

public class RightTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows:");
        int rows = scanner.nextInt();
        
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

				
			

Write a Java program to print an inverted right-angled triangle using stars.

				
					import java.util.Scanner;

public class InvertedRightTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows:");
        int rows = scanner.nextInt();
        
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

				
			

Write a Java program to print a pyramid using stars

				
					import java.util.Scanner;

public class Pyramid {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows:");
        int rows = scanner.nextInt();
        
        for (int i = 0; i < rows; i++) {
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (int k = 0; k <= i; k++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

				
			

Write a Java program to print a diamond pattern using stars.

				
					import java.util.Scanner;

public class Diamond {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows (must be odd):");
        int rows = scanner.nextInt();
        
        int spaces = rows / 2;
        int stars = 1;
        
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= stars; k++) {
                System.out.print("*");
            }
            if (i <= rows / 2) {
                spaces--;
                stars += 2;
            } else {
                spaces++;
                stars -= 2;
            }
            System.out.println();
        }
    }
}

				
			

πŸ’β€β™€οΈConclusion

These Java Programming Interview Questions For Automation Testing covers important programming concepts and will help you demonstrate your expertise in Java Programming during interviews.

🌠Best Of Luck For Your Interview! πŸ’Ό

πŸ‘You May Also LikeπŸ‘‡

Leave a comment

error: Content is protected !!