If you are planning to attempt interviews and want to learn about common coding challenges, then this article is for you. In this Mastering Java: 20 Essential Interview Questions and Answers for Programmers and QA Engineers, we are going to cover the top 20 Java program interview questions with answers.
1. Write a Java program to find the factorial of a number.
The product of all numbers up to n is known as factorial of a number and is represented by n!. For example, the value of 6! is 720.
Mathematically it is written as,
n! = 1 * 2 * 3 * 4 * … * (n-1) * n
For example, the factorial of 6 is,
6! = 1 * 2 * 3 * 4 * 5 * 6 = 720
Simple Java program to find the factorial of a number using a recursive method:
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
scanner.close();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(number);
System.out.println("The factorial of " + number + " is " + factorial);
}
}
// Recursive method to calculate factorial
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
2. Create a program to reverse a string in Java.
Java program to reverse a string:
import java.util.Scanner;
public class StringReversal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = reverseString(input);
System.out.println("Reversed string: " + reversed);
scanner.close();
}
public static String reverseString(String str) {
char[] characters = str.toCharArray();
int left = 0;
int right = characters.length - 1;
while (left < right) {
// Swap the characters at the left and right indices
char temp = characters[left];
characters[left] = characters[right];
characters[right] = temp;
// Move the indices towards the center
left++;
right--;
}
return new String(characters);
}
}
3. Write a Java program to check if a number is prime.
Java program to check if a number is prime:
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
if (num <= 3) {
return true;
}
if (num % 2 == 0 || num % 3 == 0) {
return false;
}
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
}
4. Implement a program to find the largest element in an array.
Java program to find the largest element in an array:
public class LargestElementInArray {
public static void main(String[] args) {
int[] numbers = {12, 45, 67, 90, 34, 123, 56, 78};
int largest = findLargestElement(numbers);
System.out.println("The largest element in the array is: " + largest);
}
public static int findLargestElement(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int largest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
}
5. Create a program to calculate the Fibonacci series.
Java program to calculate the Fibonacci series up to a specified number of terms:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms for the Fibonacci series: ");
int n = scanner.nextInt();
System.out.println("Fibonacci series up to " + n + " terms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
scanner.close();
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
6. Write a Java program to swap two numbers without using a third variable.
You can swap two numbers without using a third variable in Java using arithmetic operations. Here’s a Java program to do that:
public class SwapWithoutTemp {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
}
}
7. Implement a program to check if a string is a palindrome.
Java program to check if a string is a palindrome:
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
scanner.close();
}
public static boolean isPalindrome(String str) {
// Remove spaces and convert the string to lowercase for accurate comparison.
str = str.replaceAll("\\s", "").toLowerCase();
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false; // Characters don't match; not a palindrome.
}
left++;
right--;
}
return true; // If the loop completes, it's a palindrome.
}
}
8. Create a program to print the Pascal’s Triangle.
Java program to print Pascal’s Triangle:
import java.util.Scanner;
public class PascalsTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows for Pascal's Triangle: ");
int numRows = scanner.nextInt();
printPascalsTriangle(numRows);
scanner.close();
}
public static void printPascalsTriangle(int numRows) {
for (int i = 0; i < numRows; i++) {
int number = 1;
for (int j = 0; j < numRows - i; j++) {
System.out.print(" "); // Add spaces for formatting
}
for (int j = 0; j <= i; j++) {
System.out.printf("%6d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
9. Write a Java program to sort an array using the Bubble Sort algorithm.
Java program to sort an array using the Bubble Sort algorithm:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original Array:");
printArray(arr);
bubbleSort(arr);
System.out.println("\nSorted Array:");
printArray(arr);
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; 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;
swapped = true;
}
}
// If no two elements were swapped in inner loop, the array is already sorted
if (!swapped) {
break;
}
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
}
}
10. Implement a program to find the GCD (Greatest Common Divisor) of two numbers.
Java program to find the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm:
import java.util.Scanner;
public class GCDCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int gcd = findGCD(num1, num2);
System.out.println("The GCD of " + num1 + " and " + num2 + " is " + gcd);
scanner.close();
}
public static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
}
11. Create a program to find the sum of digits of a number.
Java program to find the sum of the digits of a number:
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int sum = findSumOfDigits(number);
System.out.println("The sum of the digits of " + number + " is " + sum);
scanner.close();
}
public static int findSumOfDigits(int number) {
int sum = 0;
// Loop to extract and add each digit
while (number != 0) {
int digit = number % 10;
sum += digit;
number /= 10;
}
return sum;
}
}
12. Write a Java program to generate a random number.
Java program to generate a random number:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
// Create a Random object
Random random = new Random();
// Generate and print a random integer between 0 (inclusive) and 100 (exclusive)
int randomNumber = random.nextInt(100);
System.out.println("Random Number: " + randomNumber);
}
}
13. Implement a program to calculate the area of different geometric shapes (circle, rectangle, triangle).
Java program to calculate the area of different geometric shapes: circle, rectangle, and triangle. It takes user input for the shape and relevant parameters and calculates the area accordingly:
import java.util.Scanner;
public class AreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Select a geometric shape:");
System.out.println("1. Circle");
System.out.println("2. Rectangle");
System.out.println("3. Triangle");
System.out.print("Enter the number of your choice: ");
int choice = scanner.nextInt();
double area = 0.0;
switch (choice) {
case 1:
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
area = calculateCircleArea(radius);
break;
case 2:
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
area = calculateRectangleArea(length, width);
break;
case 3:
System.out.print("Enter the base of the triangle: ");
double base = scanner.nextDouble();
System.out.print("Enter the height of the triangle: ");
double height = scanner.nextDouble();
area = calculateTriangleArea(base, height);
break;
default:
System.out.println("Invalid choice.");
break;
}
if (choice >= 1 && choice <= 3) {
System.out.println("The area of the selected shape is: " + area);
}
scanner.close();
}
// Calculate the area of a circle
public static double calculateCircleArea(double radius) {
return Math.PI * radius * radius;
}
// Calculate the area of a rectangle
public static double calculateRectangleArea(double length, double width) {
return length * width;
}
// Calculate the area of a triangle
public static double calculateTriangleArea(double base, double height) {
return 0.5 * base * height;
}
}
14. Create a program to find the factorial of a number using recursion.
Java program to find the factorial of a number using recursion:
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(n);
System.out.println("The factorial of " + n + " is: " + factorial);
}
scanner.close();
}
// Recursive method to calculate the factorial
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
15. Write a Java program to reverse a linked list.
To reverse a linked list in Java, you can create a new list by traversing the original list and inserting elements at the beginning of the new list. Here’s a simple Java program to reverse a linked list:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
void insert(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
void reverse() {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
}
public class ReverseLinkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
System.out.println("Original Linked List:");
list.display();
list.reverse();
System.out.println("Reversed Linked List:");
list.display();
}
}
16. Implement a program to find the second-highest number in an array.
You can find the second-highest number in an array in Java by iterating through the array and keeping track of the two highest numbers. Here’s a Java program to do that:
public class SecondHighestNumber {
public static int findSecondHighest(int[] arr) {
if (arr.length < 2) {
System.out.println("Array should have at least two elements");
return -1;
}
int firstMax = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int number : arr) {
if (number > firstMax) {
secondMax = firstMax;
firstMax = number;
} else if (number > secondMax && number != firstMax) {
secondMax = number;
}
}
if (secondMax == Integer.MIN_VALUE) {
System.out.println("There is no second-highest element.");
return -1;
} else {
return secondMax;
}
}
public static void main(String[] args) {
int[] arr = {10, 5, 20, 20, 8};
int secondHighest = findSecondHighest(arr);
if (secondHighest != -1) {
System.out.println("The second-highest number is: " + secondHighest);
}
}
}
17. Create a program to merge two sorted arrays.
Java program to do that:
public class MergeSortedArrays {
public static int[] merge(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int[] mergedArray = new int[n1 + n2];
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
mergedArray[k] = arr1[i];
i++;
} else {
mergedArray[k] = arr2[j];
j++;
}
k++;
}
while (i < n1) {
mergedArray[k] = arr1[i];
i++;
k++;
}
while (j < n2) {
mergedArray[k] = arr2[j];
j++;
k++;
}
return mergedArray;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] mergedArray = merge(arr1, arr2);
System.out.println("Merged Array: ");
for (int num : mergedArray) {
System.out.print(num + " ");
}
}
}
18. Write a Java program to check if a year is a leap year.
Java program to check if a year is a leap year:
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
if (isLeapYear(year)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
public static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 != 0 || (year % 100 == 0 && year % 400 == 0)) {
return true;
}
}
return false;
}
}
19. Implement a program to count the occurrences of a character in a string.
Java program to count the occurrences of a character in a string using the following code:
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to count: ");
char characterToCount = scanner.next().charAt(0);
int count = countOccurrences(inputString, characterToCount);
System.out.println("The character '" + characterToCount + "' appears " + count + " times in the string.");
scanner.close();
}
public static int countOccurrences(String str, char target) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == target) {
count++;
}
}
return count;
}
}
20. Create a program to calculate the power of a number using recursion.
Java program to calculate the power of a number using recursion with the following code:
import java.util.Scanner;
public class PowerCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
double base = scanner.nextDouble();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();
double result = calculatePower(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is " + result);
scanner.close();
}
public static double calculatePower(double base, int exponent) {
if (exponent == 0) {
return 1; // Any number raised to the power of 0 is 1.
} else if (exponent < 0) {
return 1 / (base * calculatePower(base, -exponent - 1)); // Handling negative exponents.
} else {
return base * calculatePower(base, exponent - 1);
}
}
}
Conclusion
These 20 Essential Interview Questions and Answers for Programmers and QA Engineers, will help you quickly recall most of your coding skills. Here we only covered the most frequently asked questions in interviews, which you should practice properly before attempting your interviews. This will increase your selection. Best of luck.
You may also like:
< Back