Java programs for common interview questions
Java programs for common interview questions

This guide covers frequently asked Java programs, including pattern printing, string manipulation, sorting algorithms, and OOP concepts. Prepare effectively with hands-on coding examples and explanations to boost your confidence and land your dream job! 🚀
1.Find Odd or Even Number
import java.util.Scanner; public class OddEven { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter any number: "); int number = scanner.nextInt(); if (number % 2 == 0) { System.out.println(number + " is even."); } else { System.out.println(number + " is odd."); } } }
2.Check if a Number is Prime
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(); 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 <= num / 2; i++) { if (num % i == 0) return false; } return true; } }
3.Fibonacci Series
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: "); int number = scanner.nextInt(); int first = 0, second = 1; System.out.print("Fibonacci Series: " + first + " " + second); for (int i = 2; i < number; i++) { int next = first + second; System.out.print(" " + next); first = second; second = next; } } }
4.Swap Two Numbers Without Using a Third Variable
import java.util.Scanner; public class SwapNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int a = scanner.nextInt(); System.out.print("Enter the second number: "); int b = scanner.nextInt(); System.out.println("Before Swap: a=" + a + ", b=" + b); a = a + b; b = a - b; a = a - b; System.out.println("After Swap: a=" + a + ", b=" + b); } }
5.Find Factorial of a Number
import java.util.Scanner; public class FactorialNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); int factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println("Factorial of " + number + " is: " + factorial); } }
6.Reverse a Number
import java.util.Scanner; public class ReverseNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter any number: "); int no = scanner.nextInt(); int rev = 0; while (no > 0) { int r = no % 10; rev = rev * 10 + r; no = no / 10; } System.out.println("Reversed Number: " + rev); } }
7.Check if a Number is an Armstrong Number
import java.util.Scanner; public class ArmstrongNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter any number: "); int no = scanner.nextInt(); int d = no, arm = 0; while (no > 0) { int a = no % 10; no = no / 10; arm = arm + (a * a * a); } if (d == arm) { System.out.println(d + " is an Armstrong number."); } else { System.out.println(d + " is not an Armstrong number."); } } }
8.Count Number of Digits in a Given Number
import java.util.Scanner; public class NumberOfDigits { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter any number: "); int no = scanner.nextInt(); int count = 0; while (no > 0) { no = no / 10; count++; } System.out.println("Number of digits: " + count); } }
9.Check if a Number is a Palindrome
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(); if (isPalindrome(number)) { System.out.println(number + " is a palindrome."); } else { System.out.println(number + " is not a palindrome."); } } public static boolean isPalindrome(int num) { int originalNumber = num, reversedNumber = 0; while (num > 0) { int digit = num % 10; reversedNumber = reversedNumber * 10 + digit; num /= 10; } return originalNumber == reversedNumber; } }
10.Calculate Sum of 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 = calculateSumOfDigits(number); System.out.println("Sum of digits of " + number + " is: " + sum); } public static int calculateSumOfDigits(int number) { int sum = 0; while (number > 0) { int digit = number % 10; sum += digit; number /= 10; } return sum; } }
Strings
1.) Java program to reverse a string
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); char ch; String nstr = ""; for (int i = 0; i < input.length(); i++) { ch = input.charAt(i); nstr = ch + nstr; } System.out.println("Reversed String is: " + nstr); } }
2.) Java program to reverse each word of a given string
public static void main(String[] args) { reverseEachWordOfString("Java is good programming languages"); } static void reverseEachWordOfString(String inputString) { String[] words = inputString.split(" "); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String nstr = ""; char ch; for (int j = 0; j < word.length(); j++) { ch = word.charAt(j); nstr = ch + nstr; } reverseString = reverseString + nstr + " "; } System.out.println(inputString); System.out.println(reverseString); }
3.) Java program to find duplicate characters in a string
import java.util.HashMap; import java.util.Set; public class Main { public static void main(String[] args) { duplicateCharacterCount("Learn Java Programming"); } static void duplicateCharacterCount(String inputString) { HashMap<Character, Integer> charCountMap = new HashMap<>(); char[] strArray = inputString.toCharArray(); for (char c : strArray) { if (charCountMap.containsKey(c)) { charCountMap.put(c, charCountMap.get(c) + 1); } else { charCountMap.put(c, 1); } } Set<Character> charsInString = charCountMap.keySet(); System.out.println("Duplicate Characters in : " + inputString); for (Character ch : charsInString) { if (charCountMap.get(ch) > 1) { System.out.println(ch + " : " + charCountMap.get(ch)); } } } }
4.) Java program to count occurrences of each character in a string
import java.util.HashMap; public class Main { public static void main(String[] args) { CharacterCount("Test Automation Java Automation"); } static void CharacterCount(String inputString) { HashMap<String, Integer> charCountMap = new HashMap<>(); for (String s : inputString.split(" ")) { if (charCountMap.containsKey(s)) { charCountMap.put(s, charCountMap.get(s) + 1); } else { charCountMap.put(s, 1); } } System.out.println("Count of Characters in a given string : " + charCountMap); } }
5.) Java program to count the number of words in a string
import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("Enter the String"); Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int count = 1; for (int i = 0; i < s.length() - 1; i++) { if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' ')) { count++; } } System.out.println("Number of words in a string: " + count); } }
6.) Java program to find all permutations of a given string
import java.util.Scanner; public class Main { public static void main(String[] args) { String str = "abc"; permute(str, ""); } static void permute(String str, String prefix) { if (str.length() == 0) { System.out.println(prefix); } else { for (int i = 0; i < str.length(); i++) { String rem = str.substring(0, i) + str.substring(i + 1); permute(rem, prefix + str.charAt(i)); } } } }
7.) Java program to find if a string is Palindrome
import java.util.Scanner; public class Main { public static void main(String[] args) { String str = "madam"; System.out.println(isPalindrome(str)); } static boolean isPalindrome(String str) { int start = 0; int end = str.length() - 1; while (start < end) { if (str.charAt(start) != str.charAt(end)) { return false; } start++; end--; } return true; } }
8.) Java program to determine if Two Strings are Anagrams
public class Main { public static void main(String[] args) { String str1 = "listen"; String str2 = "silent"; System.out.println(areAnagrams(str1, str2)); } static boolean areAnagrams(String str1, String str2) { if (str1.length() != str2.length()) { return false; } int[] charCount = new int[256]; for (int i = 0; i < str1.length(); i++) { charCount[str1.charAt(i)]++; charCount[str2.charAt(i)]--; } for (int count : charCount) { if (count != 0) { return false; } } return true; } }
9.) Java program to Count Vowels and Consonants in a given string
public class Main { public static void main(String[] args) { String str = "Hello World"; VowelConsonantCount(str); } static void VowelConsonantCount(String str) { int vowels = 0, consonants = 0; str = str.toLowerCase(); for (char c : str.toCharArray()) { if (c >= 'a' && c <= 'z') { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowels++; } else { consonants++; } } } System.out.println("Vowels : " + vowels); System.out.println("Consonants : " + consonants); } }
10.) Java program to print unique characters
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); System.out.println("Unique characters in \"" + input + "\":"); printUniqueCharacters(input); } public static void printUniqueCharacters(String str) { // Assume ASCII characters (0-127), use boolean array to track character occurrences boolean[] unique = new boolean[128]; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (!unique[ch]) { unique[ch] = true; System.out.print(ch + " "); } } } }
11.) Java program to print even indexed characters
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); System.out.println("Even indexed characters in \"" + input + "\":"); printEvenIndexedCharacters(input); } public static void printEvenIndexedCharacters(String str) { for (int i = 0; i < str.length(); i++) { if (i % 2 == 0) { System.out.print(str.charAt(i)); } } } }
12.) Java program to remove space from a given string
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string with spaces: "); String input = scanner.nextLine(); String stringWithoutSpaces = removeSpaces(input); System.out.println("String without spaces: " + stringWithoutSpaces); } public static String removeSpaces(String str) { StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ' ') { result.append(str.charAt(i)); } } return result.toString(); } }
13.) Java program to print each letter twice from a given string
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); String doubledString = doubleCharacters(input); System.out.println("Doubled characters: " + doubledString); } public static String doubleCharacters(String str) { StringBuilder doubled = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); doubled.append(ch).append(ch); // Append each character twice } return doubled.toString(); } }
14.) Swapping Two Strings Without Using a Third Variable
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter first string: "); String str1 = scanner.nextLine(); System.out.print("Enter second string: "); String str2 = scanner.nextLine(); System.out.println("Before swapping: str1 = " + str1 + ", str2 = " + str2); // Swapping without using a third variable str1 = str1 + str2; // Concatenate str1 and str2 and store in str1 str2 = str1.substring(0, str1.length() - str2.length()); // Extract original str1 from concatenated string str1 = str1.substring(str2.length()); // Extract original str2 System.out.println("After swapping: str1 = " + str1 + ", str2 = " + str2); } }
15.) Java Program to Compress Consecutive Characters in a String
(Example: Input: “aabbcccd”, Output: “a2b2c3d2”)
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); String output = getCharacterCount(input); System.out.println("Output: " + output); } public static String getCharacterCount(String str) { StringBuilder result = new StringBuilder(); int count = 1; for (int i = 0; i < str.length(); i++) { // If the next character is the same, increase the count if (i + 1 < str.length() && str.charAt(i) == str.charAt(i + 1)) { count++; } else { // Append the character and its count to the result result.append(str.charAt(i)).append(count); count = 1; // Reset the count } } return result.toString(); } }
16.) Java Program to Separate Uppercase and Lowercase Letters from a String
(Example: Input: “aBACbcEDed”, Output: “abcde” (lowercase) and “ABCDE” (uppercase))
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); System.out.println("Original String is: " + input); separateCharacters(input); } public static void separateCharacters(String input) { StringBuilder lowerCase = new StringBuilder(); StringBuilder upperCase = new StringBuilder(); for (char ch : input.toCharArray()) { if (Character.isLowerCase(ch)) { lowerCase.append(ch); } else { upperCase.append(ch); } } System.out.println("Output in lowercase: " + lowerCase); System.out.println("Output in uppercase: " + upperCase); } }
very informative