Cracking a Java interview requires a strong grasp of coding fundamentals and real-world problem-solving skills. Below are 25 essential Java coding interview questions, curated to challenge your logic, OOP knowledge, and understanding of Java APIs.
Java Coding Interview Questions – 2025 Updated List
1. Reverse a String Without Using Built-in Reverse Method
public static String reverse(String str) {
StringBuilder result = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
result.append(str.charAt(i));
}
return result.toString();
}
2. Check if a Number is Prime
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
3. Fibonacci Series Using Recursion
public class FibonacciRecursive {
// Recursive method to find the nth Fibonacci number
public static int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int count = 10; // Number of Fibonacci numbers to print
System.out.println("Fibonacci Series up to " + count + " terms:");
for (int i = 0; i < count; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
4. Palindrome String Checker
public static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i++) != str.charAt(j--)) return false;
}
return true;
}
5. Swap Two Variables Without Temp
int a = 10, b = 20;
a = a + b;
b = a - b;
a = a - b;
6. Count Occurrence of Characters in a String
public class SimpleCharCount {
public static void main(String[] args) {
String str = "hello world";
int[] count = new int[256]; // ASCII size
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > 0) {
System.out.println((char) i + " : " + count[i]);
}
}
}
}
7. Find Duplicate Elements in an Array
import java.util.HashSet;
import java.util.Set;
public class FindDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 1, 5, 6, 3};
Set<Integer> set = new HashSet<>();
System.out.println("Duplicate elements:");
for (int num : arr) {
if (!set.add(num)) {
System.out.println(num);
}
}
}
}
8. Sort Array Without Using Arrays.sort()
public class ManualSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 2};
// Bubble Sort logic
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print the sorted array
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
9. Find Factorial Using Recursion
public class FactorialRecursive {
// Recursive method to calculate factorial
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // base case
}
return n * factorial(n - 1); // recursive call
}
public static void main(String[] args) {
int number = 5; // You can change this to test other inputs
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
10. Check Armstrong Number
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Example (3-digit number):
153 is an Armstrong number because:
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
public static boolean isArmstrong(int num) {
int temp = num, sum = 0;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == num;
}
11. Find the Largest Element in an Array
public class FindLargest {
public static void main(String[] args) {
int[] arr = {25, 11, 67, 45, 90, 32};
int max = arr[0]; // assume first element is the largest
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; // update max if current element is greater
}
}
System.out.println("The largest element in the array is: " + max);
}
}
12. Reverse an Integer
public static int reverseInt(int num) {
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
13. Check Leap Year
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
14. Find GCD of Two Numbers
GCD stands for Greatest Common Divisor (also called Greatest Common Factor or Highest Common Factor). It is the largest positive integer that divides two or more integers without leaving a remainder.
Example:
- For numbers 12 and 18, their divisors are:
- 12: 1, 2, 3, 4, 6, 12
- 18: 1, 2, 3, 6, 9, 18
- The common divisors are: 1, 2, 3, 6
- The greatest among these is 6, so GCD(12, 18) = 6
public class GCDExample {
// Recursive method to find GCD
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String[] args) {
int num1 = 56;
int num2 = 98;
int result = gcd(num1, num2);
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + result);
}
}
15. Print All Prime Numbers from 1 to N
public class PrimeNumbersUpToN {
// Method to check if a number is prime
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 N = 50; // You can change this value
System.out.println("Prime numbers from 1 to " + N + ":");
for (int i = 1; i <= N; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
16. Sum of Digits
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
17. Find Missing Number in Array from 1 to N
public class MissingNumberFinder {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6}; // 3 is missing
int n = 6; // Expected range is 1 to 6
int expectedSum = n * (n + 1) / 2; // Sum of 1 to n
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
int missingNumber = expectedSum - actualSum;
System.out.println("Missing number is: " + missingNumber);
}
}
18. Count Even and Odd Digits
public class CountEvenOddDigits {
public static void main(String[] args) {
int number = 1234567890;
int evenCount = 0;
int oddCount = 0;
while (number > 0) {
int digit = number % 10;
if (digit % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
number /= 10;
}
System.out.println("Even digits: " + evenCount);
System.out.println("Odd digits: " + oddCount);
}
}
19. Print Fibonacci Series Iteratively
public class FibonacciIterative {
public static void main(String[] args) {
int n = 10; // Number of terms to print
int a = 0, b = 1;
System.out.print("Fibonacci Series up to " + n + " terms: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
20. Check if a Number is Palindrome
public class PalindromeNumber {
public static void main(String[] args) {
int number = 121; // You can change this number
int original = number;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
if (original == reversed) {
System.out.println(original + " is a palindrome.");
} else {
System.out.println(original + " is not a palindrome.");
}
}
}
21. Remove Duplicates from Array
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 3, 5, 1};
Set<Integer> uniqueElements = new LinkedHashSet<>();
for (int num : arr) {
uniqueElements.add(num);
}
System.out.println("Array after removing duplicates:");
for (int num : uniqueElements) {
System.out.print(num + " ");
}
}
}
22. Find Second Largest Element
public class SecondLargestElement {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found.");
} else {
System.out.println("Second largest element is: " + secondLargest);
}
}
}
23. Find Frequency of Elements
Use getOrDefault method of map to find the frequency of elements. This method Returns the value mapped to the specified key if it exists; otherwise, returns the defaultValue
you provide.
import java.util.HashMap;
import java.util.Map;
public class FrequencyOfElements {
public static void main(String[] args) {
int[] arr = {2, 3, 2, 5, 8, 6, 8, 8};
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
System.out.println("Frequency of elements:");
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}
Frequency of elements:
2 => 2
3 => 1
5 => 1
8 => 3
6 => 1
24. Java program to check if two strings are anagrams
Two strings are anagrams if they contain the same characters in any order
import java.util.Arrays;
public class AnagramCheck {
// Method to check if two strings are anagrams
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert to lowercase for case-insensitive comparison
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths differ, they can't be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to char arrays and sort
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
// Check if sorted arrays are equal
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
String s1 = "Listen";
String s2 = "Silent";
if (areAnagrams(s1, s2)) {
System.out.println(s1 + " and " + s2 + " are anagrams.");
} else {
System.out.println(s1 + " and " + s2 + " are NOT anagrams.");
}
}
}
25. Print ASCII Value of a Character
char ch = 'A';
System.out.println((int) ch);
26. Convert String to Integer
int num = Integer.parseInt("1234");
27. Convert Integer to String
String s = String.valueOf(1234);
28. Remove Whitespaces from String
String cleaned = str.replaceAll("\\s", "");
29. Java program to count the number of vowels and consonants in a given string
public class VowelsAndConsonantsCount {
public static void main(String[] args) {
String input = "Hello World";
int vowelsCount = 0;
int consonantsCount = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch >= 'a' && ch <= 'z') { // Check if it's an alphabet
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelsCount++;
} else {
consonantsCount++;
}
}
}
System.out.println("Number of vowels: " + vowelsCount);
System.out.println("Number of consonants: " + consonantsCount);
}
}
30. Find Common Elements Between Two Arrays
int[]arr1
= {10, 20, 30, 40, 50};
int[]arr
2 = {40, 50, 60, 70, 80};Set<Integer> set1 = new HashSet<>(Arrays.asList(arr1));
set1.retainAll(Arrays.asList(arr2));
31. Convert Char to String and Vice Versa
char c = 'a';
String s = Character.toString(c);
char ch = s.charAt(0);
32. Java program to find all pairs in an integer array whose sum equals a given target sum
import java.util.HashSet;
public class PairsWithGivenSum {
public static void findPairs(int[] arr, int targetSum) {
HashSet<Integer> set = new HashSet<>();
System.out.println("Pairs with sum " + targetSum + ":");
for (int num : arr) {
int complement = targetSum - num;
if (set.contains(complement)) {
System.out.println("(" + complement + ", " + num + ")");
}
set.add(num);
}
}
public static void main(String[] args) {
int[] arr = {2, 4, 3, 5, 7, 8, -1};
int targetSum = 7;
findPairs(arr, targetSum);
}
}
Pairs with sum 7:
(4, 3)
(5, 2)
(-1, 8)
33. Sort a String Alphabetically
String str = "Hello World";char[] chars = str.toCharArray();
dehllloorw
Arrays.sort(chars);
String sorted = new String(chars); //
34. Java program to find the first non-repeating character in a string
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeatingCharacter {
public static void main(String[] args) {
String input = "ABAACC";
char result = findFirstNonRepeatingChar(input);
if (result != '\0') {
System.out.println("First non-repeating character: " + result);
} else {
System.out.println("No non-repeating character found.");
}
}
public static char findFirstNonRepeatingChar(String str) {
Map<Character, Integer> charCount = new LinkedHashMap<>();
// Count frequency of each character
for (char ch : str.toCharArray()) {
charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);
}
// Find first character with count 1
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0'; // No non-repeating character found
}
}// B
35. Check if String Contains Only Digits
boolean isDigit = str.matches("\\d+");
36. Java program to count the number of words in a sentence
public class WordCount {
public static void main(String[] args) {
String sentence = "Hello world, welcome to Java programming!";
// Trim the sentence to remove leading/trailing spaces
sentence = sentence.trim();
// Split the sentence by one or more spaces
String[] words = sentence.split("\\s+");
System.out.println("Number of words: " + words.length);
}
}
37. Print Pattern (Pyramid)
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) System.out.print("*");
System.out.println();
}
38. Generate Random Number
int random = new Random().nextInt(100); // 0 to 99
39. Find Largest Word in Sentence
String str = "Java is a platform Independent Language";String[] words = str.split("\\s+");
String largest = Arrays.stream(words).max(Comparator.comparing(String::length)).orElse("");
40. Check for Balanced Parentheses
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c == '(') stack.push(c);
else if (c == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
return stack.isEmpty();
41. Java program to check if one string is a rotation of another
public class StringRotationCheck {
public static boolean isRotation(String s1, String s2) {
// Check if lengths are equal and strings are not null
if (s1 == null || s2 == null || s1.length() != s2.length()) {
return false;
}
// Concatenate s1 with itself
String concatenated = s1 + s1;
// Check if s2 is a substring of concatenated string
return concatenated.contains(s2);
}
public static void main(String[] args) {
String s1 = "rotation";
String s2 = "tationro";
if (isRotation(s1, s2)) {
System.out.println(s2 + " is a rotation of " + s1);
} else {
System.out.println(s2 + " is NOT a rotation of " + s1);
}
}
}
// tationro is a rotation of rotation
42. Replace Character in String
String str = "abcd";String modified = str.replace('a', 'x');
//xbcd
43. Java program to count how many times a specific word occurs in a sentence
public class WordOccurrenceCounter {
public static void main(String[] args) {
String sentence = "Java is great. Java is object-oriented. I love Java programming.";
String wordToFind = "Java";
int count = countWordOccurrences(sentence, wordToFind);
System.out.println("The word '" + wordToFind + "' occurs " + count + " times.");
}
public static int countWordOccurrences(String sentence, String word) {
// Normalize case to ignore case sensitivity
sentence = sentence.toLowerCase();
word = word.toLowerCase();
// Split sentence into words based on non-word characters
String[] words = sentence.split("\\W+");
int count = 0;
for (String w : words) {
if (w.equals(word)) {
count++;
}
}
return count;
}
} //The word 'Java' occurs 3 times.
Read More on Stream API.
44. Bubble Sort Algorithm
int[] arr = {3,4,1,2,7,5,8,7};for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
}
}
}
45. Java program demonstrating Linear Search to find an element in an array
public class LinearSearch {
// Method to perform linear search
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if target not found
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
int index = linearSearch(numbers, target);
if (index != -1) {
System.out.println("Element " + target + " found at index " + index);
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
} //Element 30 found at index 2
46. Java program demonstrating Binary Search on a sorted array
public class BinarySearch {
// Binary search method - returns index of target or -1 if not found
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Target found
}
if (arr[mid] < target) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Target not found
}
public static void main(String[] args) {
int[] sortedArr = {2, 4, 6, 8, 10, 12, 14};
int target = 10;
int result = binarySearch(sortedArr, target);
if (result != -1) {
System.out.println("Element " + target + " found at index " + result);
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}//Element 10 found at index 4
47. Java program demonstrating Insertion Sort
public class InsertionSort {
// Method to perform insertion sort on the array
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Move elements greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// Place key at its correct position
arr[j + 1] = key;
}
}
// Utility method to print the array
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {12, 11, 13, 5, 6};
System.out.println("Original array:");
printArray(array);
insertionSort(array);
System.out.println("Sorted array:");
printArray(array);
}
}
//Original array:
12 11 13 5 6
Sorted array:
5 6 11 12 13
48. Merge Two Sorted Arrays
import java.util.Arrays;
public class MergeAndSortArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8, 10};
// Create a new array to hold all elements
int[] merged = new int[arr1.length + arr2.length];
// Copy elements from first array
System.arraycopy(arr1, 0, merged, 0, arr1.length);
// Copy elements from second array
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);
// Sort the merged array
Arrays.sort(merged);
// Print the sorted merged array
System.out.println("Merged and sorted array:");
System.out.println(Arrays.toString(merged));
}
}
49. Java program to find the median of an array
import java.util.Arrays;
public class MedianOfArray {
public static double findMedian(int[] arr) {
Arrays.sort(arr); // Sort the array first
int n = arr.length;
if (n % 2 == 0) {
// Even length: median is average of middle two elements
return (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
} else {
// Odd length: median is middle element
return arr[n / 2];
}
}
public static void main(String[] args) {
int[] array1 = {3, 5, 1, 4, 2};
int[] array2 = {7, 8, 3, 1};
System.out.println("Median of array1: " + findMedian(array1));
System.out.println("Median of array2: " + findMedian(array2));
}
}
//Median of array1: 3.0
Median of array2: 5.0
50. Convert Decimal to Binary
String binary = Integer.toBinaryString(decimal);
Conclusion
Mastering Java coding interview questions is essential for standing out in technical interviews. This list of the top 50 Java Coding Interview Questions, along with detailed explanations, covers key areas such as strings, arrays, recursion, object-oriented concepts, and algorithmic logic. By practicing these problems, you’ll sharpen your problem-solving skills, gain confidence, and be well-prepared for real-world interviews. Whether you’re a fresher or an experienced developer, consistent practice and understanding of these questions will give you a significant edge in your Java career journey. Keep coding, keep improving! Download Java and start practicing.
- How to Use Arrays in Java (with Code Examples for Beginners)
- Compilation in Java – How It Works with Execution Flow, Steps, and Example
- How to Use loops in Java: For, While, Do‑While Explained
- How to Use If Else Statement in Java (With Examples)
- How to Understand Object-Oriented Programming in Java Easily