Top 10+ Java Interview Programs for 2024


1. Prime Number Program

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.



import java.util.Scanner; public class PrimeNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); if (isPrime(number)) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } } 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; } }


output:
Enter a number: 29 29 is a prime number.



2. Pattern Program

This program generates a pattern of numbers.


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


output:

Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5



3. Palindrome Number Program

Explanation

  1. Input Handling: The program reads an integer from the user.
  2. isPalindrome Method: This method reverses the digits of the number and compares the reversed number with the original number.
  3. Palindrome Check: If the reversed number is the same as the original number, it is a palindrome; otherwise, it is not.
import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.close(); if (isPalindrome(number)) { System.out.println(number + " is a palindrome number."); } else { System.out.println(number + " is not a palindrome number."); } } public static boolean isPalindrome(int num) { int original = num; int reversed = 0; while (num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } return original == reversed; } }

output:
Enter a number: 121
121 is a palindrome number.

Enter a number: 123
123 is not a palindrome number.


4.Sum of Array Elements
  • Reads the number of elements and the elements of the array from the user.
  • Calculates and prints the sum of the array elements using a for-each loop.



  • import java.util.Scanner; public class ArraySum { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of elements in the array: "); int n = scanner.nextInt(); int[] arr = new int[n]; System.out.println("Enter the elements of the array:"); for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } scanner.close(); int sum = calculateSum(arr); System.out.println("The sum of the array elements is: " + sum); } public static int calculateSum(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return sum; } }

    output:
    Enter the number of elements in the array: 5 Enter the elements of the array: 1 2 3 4 5 The sum of the array elements is: 15


    5. Reverse a String
  • Reads a string from the user.
  • Reverses the string using StringBuilder's reverse method and prints the reversed string.
  • import java.util.Scanner; public class ReverseString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String str = scanner.nextLine(); scanner.close(); String reversedStr = reverseString(str); System.out.println("The reversed string is: " + reversedStr); } public static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } }

    output:
    Enter a string: hello The reversed string is: olleh


    6. Second program Check if a String is a Palindrome
  • Reads a string from the user.
  • Checks if the string is a palindrome by comparing characters from both ends towards the center.
  • Prints whether the string is a palindrome or not.



  • import java.util.Scanner; public class PalindromeString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String str = scanner.nextLine(); scanner.close(); if (isPalindrome(str)) { System.out.println(str + " is a palindrome."); } else { System.out.println(str + " is not a palindrome."); } } public static boolean isPalindrome(String str) { int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } left++; right--; } return true; } }


    output:
    Enter a string: madam madam is a palindrome. Enter a string: hello hello is not a palindrome.









    1. Reverse an Array

    Code:


    import java.util.Arrays; public class ReverseArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; reverseArray(arr); System.out.println("Reversed Array: " + Arrays.toString(arr)); } public static void reverseArray(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } }

    Output:


    Reversed Array: [5, 4, 3, 2, 1]

    2. Find Maximum and Minimum in an Array

    Code:


    public class MaxMinArray { public static void main(String[] args) { int[] arr = {3, 5, 1, 4, 2}; int[] result = findMaxMin(arr); System.out.println("Maximum: " + result[0] + ", Minimum: " + result[1]); } public static int[] findMaxMin(int[] arr) { int max = arr[0]; int min = arr[0]; for (int num : arr) { if (num > max) { max = num; } if (num < min) { min = num; } } return new int[]{max, min}; } }

    Output:


    Maximum: 5, Minimum: 1

    3. Count Occurrences of an Element in an Array

    Code:


    public class CountOccurrences { public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 4, 2, 5}; int element = 2; int count = countOccurrences(arr, element); System.out.println("Element " + element + " occurs " + count + " times."); } public static int countOccurrences(int[] arr, int element) { int count = 0; for (int num : arr) { if (num == element) { count++; } } return count; } }

    Output:


    Element 2 occurs 3 times.

    4. Find Duplicates in an Array

    Code:


    import java.util.HashSet; public class FindDuplicates { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 2, 5, 1}; findDuplicates(arr); } public static void findDuplicates(int[] arr) { HashSet<Integer> seen = new HashSet<>(); HashSet<Integer> duplicates = new HashSet<>(); for (int num : arr) { if (seen.contains(num)) { duplicates.add(num); } else { seen.add(num); } } System.out.println("Duplicate elements: " + duplicates); } }

    Output:


    Duplicate elements: [1, 2]

    5. Merge Two Sorted Arrays

    Code:


    import java.util.Arrays; public class MergeSortedArrays { public static void main(String[] args) { int[] arr1 = {1, 3, 5}; int[] arr2 = {2, 4, 6}; int[] mergedArray = mergeArrays(arr1, arr2); System.out.println("Merged Array: " + Arrays.toString(mergedArray)); } public static int[] mergeArrays(int[] arr1, int[] arr2) { int[] merged = new int[arr1.length + arr2.length]; int i = 0, j = 0, k = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { merged[k++] = arr1[i++]; } else { merged[k++] = arr2[j++]; } } while (i < arr1.length) { merged[k++] = arr1[i++]; } while (j < arr2.length) { merged[k++] = arr2[j++]; } return merged; } }

    Output:


    Merged Array: [1, 2, 3, 4, 5, 6]

    6. Rotate an Array

    Code:


    import java.util.Arrays; public class RotateArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int k = 2; // Rotate by 2 positions rotateArray(arr, k); System.out.println("Rotated Array: " + Arrays.toString(arr)); } public static void rotateArray(int[] arr, int k) { k = k % arr.length; // Handle rotations greater than array length reverseArray(arr, 0, arr.length - 1); reverseArray(arr, 0, k - 1); reverseArray(arr, k, arr.length - 1); } public static void reverseArray(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } }

    Output:


    Rotated Array: [4, 5, 1, 2, 3]

    7. Check for Subarray with Zero Sum

    Code:


    import java.util.HashSet; public class SubarrayZeroSum { public static void main(String[] args) { int[] arr = {4, 2, -3, 1, 6}; boolean hasZeroSum = hasSubarrayWithZeroSum(arr); System.out.println("Does the array have a subarray with zero sum? " + hasZeroSum); } public static boolean hasSubarrayWithZeroSum(int[] arr) { HashSet<Integer> sumSet = new HashSet<>(); int sum = 0; for (int num : arr) { sum += num; if (sum == 0 || sumSet.contains(sum)) { return true; } sumSet.add(sum); } return false; } }

    Output:


    Does the array have a subarray with zero sum? true

    8. Find the Second Largest Element in an Array

    Code:


    public class SecondLargest { public static void main(String[] args) { int[] arr = {3, 5, 1, 4, 2}; int secondLargest = findSecondLargest(arr); System.out.println("Second Largest Element: " + secondLargest); } public static int findSecondLargest(int[] arr) { int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int num : arr) { if (num > first) { second = first; first = num; } else if (num > second && num < first) { second = num; } } return second; } }

    Output:


    Second Largest Element: 4

    9. Find Unique Elements in an Array

    Code:


    import java.util.HashMap; import java.util.Map; public class UniqueElements { public static void main(String[] args) { int[] arr = {1, 2, 3, 2, 4, 1, 5}; System.out.println("Unique elements: "); findUniqueElements(arr); } public static void findUniqueElements(int[] arr) { Map<Integer, Integer> elementCount = new HashMap<>(); for (int num : arr) { elementCount.put(num, elementCount.getOrDefault(num, 0) + 1); } for (Map.Entry<Integer, Integer> entry : elementCount.entrySet()) { if (entry.getValue() == 1) { System.out.print(entry.getKey() + " "); } } System.out.println(); } }

    Output:


    Unique elements: 3 4 5

    10. Find Intersection of Two Arrays

    Code:


    import java.util.HashSet; public class ArrayIntersection { public static void main(String[] args) { int[] arr1 = {1, 2, 2, 1}; int[] arr2 = {2, 2}; System.out.println("Intersection: "); findIntersection(arr1, arr2); } public static void findIntersection(int[] arr1, int[] arr2) { HashSet<Integer> set = new HashSet<>(); for (int num : arr1) { set.add(num); } for (int num : arr2) { if (set.contains(num)) { System.out.print(num + " "); set.remove(num); } } System.out.println(); } }

    Output:


    Intersection: 2

    11. Check if Array is Sorted

    Code:


    public class CheckSortedArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; boolean isSorted = isArraySorted(arr); System.out.println("Is the array sorted? " + isSorted); } public static boolean isArraySorted(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i - 1]) { return false; } } return true; } }

    Output:


    Is the array sorted? true

    12. Remove Duplicates from an Array

    Code:

    import java.util.Arrays;
    public class RemoveDuplicates { public static void main(String[] args) { int[] arr = {1, 2, 3, 2, 4, 1, 5}; int[] result = removeDuplicates(arr); System.out.println("Array after removing duplicates: " + Arrays.toString(result)); } public static int[] removeDuplicates(int[] arr) { return Arrays.stream(arr).distinct().toArray(); } }

    Output:


    Array after removing duplicates: [1, 2, 3, 4, 5]

    13. Find Missing Number in Array

    Code:

    public class FindMissingNumber {
    public static void main(String[] args) { int[] arr = {3, 7, 1, 2, 8, 4, 5}; // Numbers from 1 to 8 int missingNumber = findMissingNumber(arr, 8); System.out.println("Missing Number: " + missingNumber); } public static int findMissingNumber(int[] arr, int n) { int total = n * (n + 1) / 2; // Sum of first n natural numbers int sum = 0; for (int num : arr) { sum += num; } return total - sum; } }

    Output:


    Missing Number: 6

    14. Kth Largest Element in an Array

    Code:


    import java.util.Arrays; public class KthLargestElement { public static void main(String[] args) { int[] arr = {3, 2, 1, 5, 6, 4}; int k = 2; // 2nd largest int kthLargest = findKthLargest(arr, k); System.out.println(k + "th Largest Element: " + kthLargest); } public static int findKthLargest(int[] arr, int k) { Arrays.sort(arr); return arr[arr.length - k]; } }

    Output:


    2th Largest Element: 5

    15. Check if Two Arrays are Equal

    Code:


    import java.util.Arrays; public class CheckEqualArrays { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; boolean areEqual = areArraysEqual(arr1, arr2); System.out.println("Are the two arrays equal? " + areEqual); } public static boolean areArraysEqual(int[] arr1, int[] arr2) { return Arrays.equals(arr1, arr2); } }

    Output:


    Are the two arrays equal? true

    16. Sum of All Elements in an Array

    Code:


    public class SumOfArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int sum = sumArray(arr); System.out.println("Sum of Array Elements: " + sum); } public static int sumArray(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return sum; } }

    Output:


    Sum of Array Elements: 15

    17. Find the Majority Element

    Code:


    import java.util.HashMap; public class MajorityElement { public static void main(String[] args) { int[] arr = {2, 2, 1, 1, 1, 2, 2}; int majorityElement = findMajorityElement(arr); System.out.println("Majority Element: " + majorityElement); } public static int findMajorityElement(int[] arr) { HashMap<Integer, Integer> countMap = new HashMap<>(); int n = arr.length; for (int num : arr) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); if (countMap.get(num) > n / 2) { return num; } } return -1; // No majority element found } }

    Output:


    Majority Element: 2

    18. Find Common Elements in Three Arrays

    Code:


    import java.util.HashSet; public class CommonElements { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {2, 3, 6}; int[] arr3 = {3, 4, 7}; System.out.println("Common Elements: "); findCommonElements(arr1, arr2, arr3); } public static void findCommonElements(int[] arr1, int[] arr2, int[] arr3) { HashSet<Integer> set1 = new HashSet<>(); for (int num : arr1) { set1.add(num); } HashSet<Integer> common = new HashSet<>(); for (int num : arr2) { if (set1.contains(num)) { common.add(num); } } for (int num : arr3) { if (common.contains(num)) { System.out.print(num + " "); } } System.out.println(); } }

    Output:


    Common Elements: 3

    19. Print Elements in Wave Order

    Code:


    public class WaveArray { public static void main(String[] args) { int[][] arr = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; System.out.println("Wave Order: "); printWave(arr); } public static void printWave(int[][] arr) { for (int j = 0; j < arr[0].length; j++) { if (j % 2 == 0) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i][j] + " "); } } else { for (int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i][j] + " "); } } } System.out.println(); } }

    Output:


    Wave Order: 1 5 9 2 6 10 3 7 11 4 8 12

    20. Find the Maximum Product of Two Integers in an Array

    Code:


    public class MaxProduct { public static void main(String[] args) { int[] arr = {1, 5, 3, 9, 2}; int maxProduct = findMaxProduct(arr); System.out.println("Maximum Product of Two Integers: " + maxProduct); } public static int findMaxProduct(int[] arr) { if (arr.length < 2) { return 0; // Not enough elements } int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE; for (int num : arr) { if (num > max1) { max2 = max1; max1 = num; } else if (num > max2) { max2 = num; } } return max1 * max2; } }

    Output:


    Maximum Product of Two Integers: 45

    0 Comments:

    Post a Comment