Frequently asked Java Programming Interview questions with answers and explanations.
1. Prime Number Program in Java
Explanation: This program checks whether a given number is prime. A prime number is a number greater than 1 that has no divisors other than 1 and itself. We test divisibility from 2 up to the square root of the number.
public class PrimeNumber {
public static boolean isPrime(int number) {
if (number <= 1) return false; // Step 1: Prime numbers are greater than 1
for (int i = 2; i <= Math.sqrt(number); i++) { // Step 2: Loop from 2 to sqrt(number)
if (number % i == 0) return false; // Step 3: If divisible, it's not prime
}
return true; // Step 4: If no divisors found, it is prime
}
public static void main(String[] args) {
int number = 29;
System.out.println(number + " is prime: " + isPrime(number)); // Example number 29
}
}
Trace:
- Input:
number = 29
isPrime(29)
number > 1
is true- Loop from
i = 2
tosqrt(29)
(approximately 5.39)29 % 2 != 0
29 % 3 != 0
29 % 4 != 0
29 % 5 != 0
- No divisors found, return
true
Example Output:
29 is prime: true
2. Factorial Program in Java
Explanation: This program calculates the factorial of a number using recursion. The factorial of a number is the product of all positive integers up to that number.
public class Factorial {
public static int factorial(int number) {
if (number == 0) return 1; // Step 1: Base case: 0! = 1
return number * factorial(number - 1); // Step 2: Recursive call
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number)); // Example number 5
}
}
Trace:
- Input:
number = 5
factorial(5)
number != 0
, so return5 * factorial(4)
factorial(4)
number != 0
, so return4 * factorial(3)
factorial(3)
number != 0
, so return3 * factorial(2)
factorial(2)
number != 0
, so return2 * factorial(1)
factorial(1)
number != 0
, so return1 * factorial(0)
factorial(0)
number == 0
, so return1
- Return:
1 * 1 = 1
,2 * 1 = 2
,3 * 2 = 6
,4 * 6 = 24
,5 * 24 = 120
Example Output:
Factorial of 5 is: 120
3. Palindrome Program in Java
Explanation: This program checks whether a given number is a palindrome. A palindrome reads the same forwards and backwards.
public class Palindrome {
public static boolean isPalindrome(int number) {
int original = number;
int reversed = 0;
while (number != 0) { // Step 1: Reverse the number
int digit = number % 10; // Step 2: Extract the last digit
reversed = reversed * 10 + digit; // Step 3: Build the reversed number
number /= 10; // Step 4: Remove the last digit
}
return original == reversed; // Step 5: Compare original and reversed
}
public static void main(String[] args) {
int number = 121;
System.out.println(number + " is palindrome: " + isPalindrome(number)); // Example number 121
}
}
Trace:
- Input:
number = 121
isPalindrome(121)
original = 121
,reversed = 0
- Loop:
number = 121
,digit = 1
,reversed = 0 * 10 + 1 = 1
,number = 12
number = 12
,digit = 2
,reversed = 1 * 10 + 2 = 12
,number = 1
number = 1
,digit = 1
,reversed = 12 * 10 + 1 = 121
,number = 0
original == reversed
(121 == 121), returntrue
Example Output:
121 is palindrome: true
4. Even Odd Program in Java
Explanation: This program checks whether a given number is even or odd. An even number is divisible by 2, while an odd number is not.
public class EvenOdd {
public static boolean isEven(int number) {
return number % 2 == 0; // Check if the number is divisible by 2
}
public static void main(String[] args) {
int number = 10;
System.out.println(number + " is even: " + isEven(number)); // Example number 10
System.out.println(number + " is odd: " + !isEven(number)); // Example number 10
}
}
Trace:
- Input:
number = 10
isEven(10)
10 % 2 == 0
is true, returntrue
!isEven(10)
!true
is false, returnfalse
Example Output:
10 is even: true
10 is odd: false
5. Anagram Program in Java
Explanation: This program checks whether two strings are anagrams. An anagram is a word formed by rearranging the letters of another word. The program sorts the characters of both strings and compares them.
import java.util.Arrays;
public class Anagram {
public static boolean isAnagram(String str1, String str2) {
if (str1.length() != str2.length()) return false; // Step 1: Check if lengths are equal
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1); // Step 2: Sort the characters
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2); // Step 3: Compare sorted arrays
}
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
System.out.println(str1 + " and " + str2 + " are anagrams: " + isAnagram(str1, str2)); // Example strings
}
}
Trace:
- Input:
str1 = "listen"
,str2 = "silent"
isAnagram("listen", "silent")
- Lengths are equal
- Convert to char arrays:
['l', 'i', 's', 't', 'e', 'n']
,['s', 'i', 'l', 'e', 'n', 't']
- Sort arrays:
['e', 'i', 'l', 'n', 's', 't']
,['e', 'i', 'l', 'n', 's', 't']
- Arrays are equal, return
true
Example Output:
listen and silent are anagrams: true
6. Fibonacci Series Program in Java
Explanation: This program generates the Fibonacci series up to a given number. The Fibonacci series is a sequence where each number is the sum of the two preceding ones.
public class FibonacciSeries {
public static void fibonacci(int count) {
int n1 = 0, n2 = 1;
System.out.print(n1 + " " + n2); // Step 1: Print the first two numbers
for (int i = 2; i < count; i++) {
int n3 = n1 + n2; // Step 2: Compute the next number
System.out.print(" " + n3); // Step 3: Print the next number
n1 = n2; // Step 4: Update n1 and n2
n2 = n3;
}
}
public static void main(String[] args) {
int count = 10;
fibonacci(count); // Example count
}
}
Trace:
- Input:
count = 10
fibonacci(10)
- Print
0 1
- Loop from
i = 2
to9
n3 = 0 + 1 = 1
, print1
, updaten1 = 1
, `n2
- Print
= 1 -
n3 = 1 + 1 = 2, print
2, update
n1 = 1,
n2 = 2 -
n3 = 1 + 2 = 3, print
3, update
n1 = 2,
n2 = 3 -
n3 = 2 + 3 = 5, print
5, update
n1 = 3,
n2 = 5 -
n3 = 3 + 5 = 8, print
8, update
n1 = 5,
n2 = 8 -
n3 = 5 + 8 = 13, print
13, update
n1 = 8,
n2 = 13 -
n3 = 8 + 13 = 21, print
21, update
n1 = 13,
n2 = 21 -
n3 = 13 + 21 = 34, print
34, update
n1 = 21,
n2 = 34`
Example Output:
0 1 1 2 3 5 8 13 21 34
7. Java Program to Reverse a String
Explanation: This program reverses a given string. We use a StringBuilder
to reverse the string and then convert it back to a string.
public class ReverseString {
public static String reverse(String str) {
StringBuilder sb = new StringBuilder(str); // Step 1: Create a StringBuilder
return sb.reverse().toString(); // Step 2: Reverse and convert to string
}
public static void main(String[] args) {
String str = "hello";
System.out.println("Reverse of " + str + " is: " + reverse(str)); // Example string
}
}
Trace:
- Input:
str = "hello"
reverse("hello")
- Create
StringBuilder
with “hello” - Reverse: “olleh”
- Convert to string: “olleh”
- Create
Example Output:
Reverse of hello is: olleh
8. Magic Number Program in Java
Explanation: A magic number is a number in which the eventual sum of the digits is 1 when repeated summation of the digits is performed. For example, 19 is a magic number because 1+9=10, 1+0=1.
public class MagicNumber {
public static boolean isMagic(int number) {
while (number > 9) { // Step 1: Repeat until number is a single digit
int sum = 0;
while (number != 0) { // Step 2: Sum the digits
sum += number % 10;
number /= 10;
}
number = sum; // Step 3: Update number with sum
}
return number == 1; // Step 4: Check if the single digit is 1
}
public static void main(String[] args) {
int number = 19;
System.out.println(number + " is magic: " + isMagic(number)); // Example number
}
}
Trace:
- Input:
number = 19
isMagic(19)
number > 9
sum = 0
,number = 19
sum += 19 % 10
(9),number /= 10
(1)sum += 1
(10),number = 0
number = 10
number > 9
sum = 0
,number = 10
sum += 10 % 10
(0),number /= 10
(1)sum += 1
(1),number = 0
number = 1
number == 1
, returntrue
Example Output:
19 is magic: true
9. Armstrong Number Program in Java
Explanation: An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
public class ArmstrongNumber {
public static boolean isArmstrong(int number) {
int original = number, sum = 0;
int digits = String.valueOf(number).length(); // Step 1: Calculate the number of digits
while (number != 0) {
int digit = number % 10; // Step 2: Extract the last digit
sum += Math.pow(digit, digits); // Step 3: Raise the digit to the power of digits and add to sum
number /= 10; // Step 4: Remove the last digit
}
return sum == original; // Step 5: Check if sum is equal to original number
}
public static void main(String[] args) {
int number = 153;
System.out.println(number + " is Armstrong: " + isArmstrong(number)); // Example number
}
}
Trace:
- Input:
number = 153
isArmstrong(153)
original = 153
,sum = 0
,digits = 3
- Loop:
digit = 153 % 10
(3),sum += 3^3
(27),number /= 10
(15)digit = 15 % 10
(5),sum += 5^3
(125),number /= 10
(1)digit = 1 % 10
(1),sum += 1^3
(1),number = 0
sum == original
(153 == 153), returntrue
Example Output:
153 is Armstrong: true
10. Bubble Sort Program in Java
Explanation: Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) { // Step 1: Loop through all elements
for (int j = 0; j < n - i - 1; j++) { // Step 2: Compare adjacent elements
if (arr[j] > arr[j + 1]) { // Step 3: Swap if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr); // Example array
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Trace:
- Input:
arr = {64, 34, 25, 12, 22, 11, 90}
bubbleSort(arr)
- First pass:
64 > 34
, swap to{34, 64, 25, 12, 22, 11, 90}
64 > 25
, swap to{34, 25, 64, 12, 22, 11, 90}
64 > 12
, swap to{34, 25, 12, 64, 22, 11, 90}
64 > 22
, swap to{34, 25, 12, 22, 64, 11, 90}
64 > 11
, swap to{34, 25, 12, 22, 11, 64, 90}
- Continue passes until the array is sorted
- First pass:
Example Output:
Sorted array: 11 12 22 25 34 64 90
For more star pattern programs, check out this 10 Star Java Pattern Program Interview Questions. Additionally, explore more number patterns at Number Patterns Program Interview Questions.
For More Java Programming Interview Questions
- Java Exception Handling: A Comprehensive Guide
- Python Machine Learning Libraries: A Comprehensive Guide
- Java Collections Framework Tutorial
- Java Quiz Contest – Participate now and get personalized guidance to crack your interview!
- 30+ Important Java Scenario Based Interview Questions 2024