Java programming Interview Questions for beginners/experienced professionals from Codingcompiler. These Java programming interview questions were asked in various interviews conducted by top multinational companies across the globe. We hope that these interview questions will help you in cracking your next Java programming job interview. All the best and happy learning.
Java Programming Interview Questions and Answers
Q. Write a Java program to print Fibonacci series up to a given number or create simple Java program to calculate Fibonacci number?
Q. Write a program on prime number?
Q. Write a palindrome program where number or string is predefined?Q. Write a program to find a given number is prime number program in Java?
Q. Find Factorial of a number using while loop
Q. Write a Java Program to removed duplicates from ArrayList?
Q. How to check if two String are Anagram in Java?
Q. Write a java program to implement bubble sort?
Q. Write a Java program to multiply two matrix?
Q. Write a Java Program to reverse a string without using String inbuilt function.
Q. Write a Java program to remove leading whitespaces with regular expression?
Q. How to create a pyramid of numbers in java?
Q. 5 Methods To Find Duplicates In Array In Java
Q. How to find occurrence of a each character in a string
Q. How to find sum of all digits of a number in java?
Q. Java Program to check an Armstrong numbe
Java Programming Interview Questions With Solutions
Q. Write a Java program to print Fibonacci series up to a given number or create simple Java program to calculate Fibonacci number?
Answer:
Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series, we create a function to calculate Fibonacci number and then print those numbers on Java console.
import java.util.Scanner;
/**
* Java program to calculate and print Fibonacci number using both recursion
* and Iteration.
* Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2
* first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
*/
public class FibonacciCalculator {
public static void main(String args[]) {
//input to print Fibonacci series upto how many numbers
System.out.println(“Enter number upto which Fibonacci series to print: “);
int number = new Scanner(System.in).nextInt();
System.out.println(“Fibonacci series upto ” + number +” numbers : “);
//printing Fibonacci series upto number
for(int i=1; i<=number; i++){
System.out.print(fibonacci2(i) +” “);
}
}
/*
* Java program for Fibonacci number using recursion.
* This program uses tail recursion to calculate Fibonacci number for a given number
* @return Fibonacci number
*/
public static int fibonacci(int number){
if(number == 1 || number == 2){
return 1;
}
return fibonacci(number-1) + fibonacci(number -2); //tail recursion
}
/*
* Java program to calculate Fibonacci number using loop or Iteration.
* @return Fibonacci number
*/
public static int fibonacci2(int number){
if(number == 1 || number == 2){
return 1;
}
int fibo1=1, fibo2=1, fibonacci=1;
for(int i= 3; i<= number; i++){
//Fibonacci number is sum of previous two Fibonacci number
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci; //Fibonacci number
}
}
Output:
Enter number upto which Fibonacci series to print:
12
Fibonacci series upto 12 numbers :
1 1 2 3 5 8 13 21 34 55 89 144
Q. Write a program on prime number?
Answer:
import java.util.Scanner;
/**
* Java Program to check if a number is Prime or Not. This program accepts a
* number from command prompt and check if it is prime or not.
*
* @author https://java67.blogspot.com
*/
public class Testing {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println(“Enter number to check if prime or not “);
while (number != 0) {
number = scnr.nextInt();
System.out.printf(“Does %d is prime? %s %s %s %n”, number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* @return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible – no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return “not valid”;
}
if (num == 0 || num == 1) {
return “not prime”;
}
if (num == 2 || num == 3) {
return “prime number”;
}
if ((num * num – 1) % 24 == 0) {
return “prime”;
} else {
return “not prime”;
}
}
}
Output
Enter number to check if prime or not
2? Does 2 is prime? true prime number true
3? Does 3 is prime? true prime number true
4? Does 4 is prime? false not prime false
5? Does 5 is prime? true prime true
6? Does 6 is prime? false not prime false
7? Does 7 is prime? true prime true
17? Does 17 is prime? true prime true
21? Does 21 is prime? false not prime false
131? Does 131 is prime? true prime true
139? Does 139 is prime? true prime true
Q. Write a palindrome program where number or string is predefined?
Solution:
Let’s see the palindrome program in java. In this java program, we will get a number variable and check whether number is palindrome or not.
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = “”; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println(“Enter a string/number to check if it is a palindrome”);
original = in.nextLine();
int length = original.length();
for ( int i = length – 1; i >= 0; i– )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println(“Entered string/number is a palindrome.”);
else
System.out.println(“Entered string/number isn’t a palindrome.”);
}
}
Q. Write a program to find a given number is prime number program in Java?
Solution:
import java.util.Scanner;
import java.util.Scanner;
public class PrimeExample3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(“Enter a number : “);
int n = s.nextInt();
if (isPrime(n)) {
System.out.println(n + ” is a prime number”);
} else {
System.out.println(n + ” is not a prime number”);
}
}
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;
}
}
Q. Find Factorial of a number using while loop
public class Factorial {
public static void main(String[] args) {
int num = 5, i = 1;
long factorial = 1;
while(i <= num)
{
factorial *= i;
i++;
}
System.out.printf(“Factorial of %d = %d”, num, factorial);
}
}
When you run the program, the output will be:
Output:
Factorial of 5 = 120
Frequently asked Java programming Interview Questions
Q. Write a Java Program to removed duplicates from ArrayList?
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Java Program to remove repeated elements from ArrayList in Java.
*
* @author WINDOWS 8
*/
public class ArrayListDuplicateDemo{
public static void main(String args[]){
// creating ArrayList with duplicate elements
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7); //duplicate
primes.add(7);
primes.add(11);
// let’s print arraylist with duplicate
System.out.println(“list of prime numbers : ” + primes);
// Now let’s remove duplicate element without affecting order
// LinkedHashSet will guaranteed the order and since it’s set
// it will not allow us to insert duplicates.
// repeated elements will automatically filtered.
Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(primes);
// now let’s clear the ArrayList so that we can copy all elements from LinkedHashSet
primes.clear();
// copying elements but without any duplicates
primes.addAll(primesWithoutDuplicates);
System.out.println(“list of primes without duplicates : ” + primes);
}
}
Output
list of prime numbers : [2, 3, 5, 7, 7, 11]
list of primes without duplicates : [2, 3, 5, 7, 11]
Q. How to check if two String are Anagram in Java?
Answer:
import java.util.Arrays;
/**
* Java program – String Anagram Example.
* This program checks if two Strings are anagrams or not
*
*
*/
public class AnagramCheck {
/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* @return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}
char[] chars = word.toCharArray();
for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
}else{
return false;
}
}
return anagram.isEmpty();
}
/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* @return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);
return Arrays.equals(charFromWord, charFromAnagram);
}
public static boolean checkAnagram(String first, String second){
char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);
for(char ch : characters){
int index = sbSecond.indexOf(“” + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}
return sbSecond.length()==0 ? true : false;
}
}
Q. Write a java program to implement bubble sort?
Answer:
public class BubbleSort {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j=1; j < (n-i); j++) {
if(arr[j-1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
System.out.println(“Array Before Bubble Sort”);
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ” “);
}
System.out.println();
bubbleSort(arr);
System.out.println(“Array After Bubble Sort”);
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ” “);
}
}
}
Output
Array Before Bubble Sort
2 5 -2 6 -3 8 0 -7 -9 4
Array After Bubble Sort
-9 -7 -3 -2 0 2 4 5 6 8
Q. Write a Java program to multiply two matrix?
Sol:
Java matrix multiplication
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println(“Enter the number of rows and columns of first matrix”);
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println(“Enter elements of first matrix”);
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println(“Enter the number of rows and columns of second matrix”);
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println(“The matrices can’t be multiplied with each other.”);
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println(“Enter elements of second matrix”);
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
second[c][d] = in.nextInt();
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++)
sum = sum + first[c][k]*second[k][d];
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println(“Product of the matrices:”);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+”\t”);
System.out.print(“\n”);
}
}
}
}
Output:
Enter the number of rows and coloumns of first matrix
3 3
Enter the elements of first matrix
1 2 3
4 5 6
7 8 9
Enter the number of rows and coloumns of second matrix
3 3
Enter the elements of second matrix
9 8 7
6 5 4
3 2 1
Product of entered matrices
30 24 18
84 69 54
138 114 90
Advanced Java programming Interview Questions for Experienced
Q. Write a Java Program to reverse a string without using String inbuilt function.
Answer:
import java.util.Scanner;
public class ReverseSplit {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str;
Scanner in = new Scanner(System.in);
System.out.println(“Enter your String”);
str = in.nextLine();
String[] token = str.split(“”); //used split method to print in reverse order
for(int i=token.length-1; i>=0; i–)
{
System.out.print(token[i] + “”);
}
}
}
Output:
Enter your String
Softwaretestinghelp
plehgnitseterawtfoS
Q. Write a Java program to remove leading whitespaces with regular expression?
Answer:
public class StringRemoveWhiteSpace {
public static void main(String args[]) {
//removing white space from String from beginning and end in Java
String strWhiteSpace = ” This String contains White Space at beginning and end and middle “;
System.out.printf(“String before removing White space : %n %s %n”, strWhiteSpace);
System.out.printf(“length of String before removing white space %d : “, strWhiteSpace.length());
//trim() method can remove white space from beginning and end of String in Java
String strWithoutWhiteSpace = strWhiteSpace.trim();
System.out.printf(“String after removing white space from beginning and end %n %s %n”, strWithoutWhiteSpace);
System.out.printf(“length of String after removing white space from beginning and end %d : “, strWithoutWhiteSpace.length());
//removing white space between String in Java
String white space = “ABC DEF GHI”;
System.out.println(“String with white space between words: ” + white space);
// \s is regular expression for white space tab etc
String withoutspace = whitespace.replaceAll(“\\s”, “”);
System.out.println(“String after removing white space between words and everywhere: ” + withoutspace);
}
}
Output:
String before removing White space :
This String contains White Space at beginning and end and middle
length of String before removing white space 72 : String after removing white space from beginning and end
This String contains White Space at beginning and end and middle
length of String after removing white space from beginning and end 64 : String with white space between words: ABC DEF GHI
String after removing white space between words and everywhere: ABCDEFGHI
Q. How to create a pyramid of numbers in java?
Solution:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Taking noOfRows value from the user
System.out.println(“How Many Rows You Want In Your Pyramid?”);
int noOfRows = sc.nextInt();
//Initializing rowCount with 1
int rowCount = 1;
System.out.println(“Here Is Your Pyramid”);
//Implementing the logic
for (int i = noOfRows; i >= 1; i–) {
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++) {
System.out.print(” “);
}
//Printing j where j value will be from i to noOfRows
for (int j = i; j <= noOfRows; j++) {
System.out.print(j+” “);
}
//Printing j where j value will be from noOfRows-1 to i
for (int j = noOfRows-1; j >= i; j–) {
System.out.print(j+” “);
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}
}
}
Output:
Here is the Pyramid
Q. 5 Methods To Find Duplicates In Array In Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
public class DuplicatesInArray
{
//Method 1 : Brute Force Method
private static void findDuplicatesUsingBruteForce(int[] inputArray)
{
for (int i = 0; i < inputArray.length; i++)
{
for (int j = i+1; j < inputArray.length; j++)
{
if(inputArray[i] == inputArray[j])
{
System.out.println(“Duplicate Element : “+inputArray[i]);
}
}
}
}
//Method 2 : Sorting Method
private static void findDuplicatesUsingSorting(int[] inputArray)
{
Arrays.sort(inputArray);
for (int i = 0; i < inputArray.length-1; i++)
{
if(inputArray[i] == inputArray[i+1])
{
System.out.println(“Duplicate Element : ” + inputArray[i]);
}
}
}
//Method 3 : Using HashSet
private static void findDuplicatesUsingHashSet(int[] inputArray)
{
HashSet<Integer> set = new HashSet<Integer>();
for (int element : inputArray)
{
if( ! set.add(element))
{
System.out.println(“Duplicate Element : “+element);
}
}
}
//Method 4 : Using HashMap
private static void findDuplicatesUsingHashMap(int[] inputArray)
{
HashMap<Integer, Integer> map = new HashMap<>();
for (int element : inputArray)
{
if(map.get(element) == null)
{
map.put(element, 1);
}
else
{
map.put(element, map.get(element)+1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet)
{
if(entry.getValue() > 1)
{
System.out.println(“Duplicate Element : “+entry.getKey()+” – found “+entry.getValue()+” times.”);
}
}
}
//Method 5 : Using Java 8 Streams
private static void findDuplicatesUsingJava8(int[] inputArray)
{
Set<Integer> uniqueElements = new HashSet<>();
Set<Integer> duplicateElements = Arrays.stream(inputArray)
.filter(i -> !uniqueElements.add(i))
.boxed()
.collect(Collectors.toSet());
System.out.println(duplicateElements);
}
public static void main(String[] args)
{
int[] inputArray = new int[] {111, 333, 555, 777, 333, 444, 555};
System.out.println(“======Duplicates Using Brute Force======”);
findDuplicatesUsingBruteForce(inputArray);
System.out.println(“======Duplicates Using Sorting======”);
findDuplicatesUsingSorting(inputArray);
System.out.println(“======Duplicates Using HashSet======”);
findDuplicatesUsingHashSet(inputArray);
System.out.println(“======Duplicates Using HashMap======”);
findDuplicatesUsingHashMap(inputArray);
System.out.println(“======Duplicates Using Java 8 Streams======”);
findDuplicatesUsingJava8(inputArray);
}
}
Output :
======Duplicates Using Brute Force======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using Sorting======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using HashSet======
Duplicate Element : 333
Duplicate Element : 555
======Duplicates Using HashMap======
Duplicate Element : 555 – found 2 times.
Duplicate Element : 333 – found 2 times.
======Duplicates Using Java 8 Streams======
[555, 333]
Q. How to find occurrence of a each character in a string
Sol:
class JavaExample {
static void countEachChar(String str)
{
//ASCII values ranges upto 256
int counter[] = new int[256];
//String length
int len = str.length();
/* This array holds the occurrence of each char, For example
* ASCII value of A is 65 so if A is found twice then
* counter[65] would have the value 2, here 65 is the ASCII value
* of A
*/
for (int i = 0; i < len; i++)
counter[str.charAt(i)]++;
// We are creating another array with the size of String
char array[] = new char[str.length()];
for (int i = 0; i < len; i++) {
array[i] = str.charAt(i);
int flag = 0;
for (int j = 0; j <= i; j++) {
/* If a char is found in String then set the flag
* so that we can print the occurrence
*/
if (str.charAt(i) == array[j])
flag++;
}
if (flag == 1)
System.out.println(“Occurrence of char ” + str.charAt(i)
+ ” in the String is:” + counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = “java”;
countEachChar(str);
}
}
Output:
Occurrence of chat j in the string is:1
Occurrence of chat a in the string is:2
Occurrence of chat v in the string is: 1
Top Java programming Interview Questions
Q. How to find sum of all digits of a number in java?
Sol:
import java.util.Scanner;
public class AddDigits
{
public static void main(String args[])
{
// initializing and declaring the objects.
int num, rem=0, sum=0, temp;
Scanner scan = new Scanner(System.in);
// enter number here.
System.out.print(“Enter the Number : “);
num = scan.nextInt();
// temp is to store number.
temp = num;
while(num>0)
{
rem = num%10;
sum = sum+rem;
num = num/10;
}
System.out.print(“Sum of Digits of ” +temp+ ” is : ” +sum);
}
}
Output:
First run:
Enter the Number : 582
Sum of Digits of 582 is : 15
Second run:
Enter the Number : 256868
Sum of Digits of 256868 is : 35
Q. Java Program to check an Armstrong number
You can check whether a given number is Armstrong number or not in Java in two ways:
- Using ‘while’ loop
- Java ‘for’ loop
Using ‘while’ loop
In case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. The example program below checks if a given 3 digit number is Armstrong number or not.
package MyPackage;
public class ArmstrongNumber{
public static void main(String[] args) {
int num = 371, originalNum, remainder, result = 0;
originalNum = num;
while (originalNum != 0)
{
remainder = originalNum % 10;
result += Math.pow(remainder, 3);
originalNum /= 10;
}
if(result == num)
System.out.println(num + ” is an Armstrong number.”);
else
System.out.println(num + ” is not an Armstrong number.”);
}
}
Output: 371 is an Armstrong number.
Q. How to check whether given number is binary or not?
Sol:
package com.java2novice.algos;
public class MyBinaryCheck {
public boolean isBinaryNumber(int binary){
boolean status = true;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
if(tmp > 1){
status = false;
break;
}
binary = binary/10;
}
}
return status;
}
public static void main(String a[]){
MyBinaryCheck mbc = new MyBinaryCheck();
System.out.println(“Is 1000111 binary? :”+mbc.isBinaryNumber(1000111));
System.out.println(“Is 10300111 binary? :”+mbc.isBinaryNumber(10300111));
}
}
Output:
Is 1000111 binary? :true
Is 10300111 binary? :false
Q. Write a program find the GCD of two numbers?
Sol:
import java.util.*;
class gcd
{
public static void main(String args[])
{
int n1,n2,i,min,gcd=1;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter two integers”);
n1=sc.nextInt();
n2=sc.nextInt();
min = (n1<n2)?n1:n2;
for(i=1;i<=min;i++)
{
// Checks if i is factor of n1 &n2
if(n1%i==0 && n2%i==0)
{
gcd = i;
}
}
System.out.println(“G.C.D of “+n1+” and “+n2+” = “+gcd);
}
}
Output:
Enter two integers
12
8
GCD of 12 and 8 = 4
RELATED INTERVIEW QUESTIONS
- Core Java Interview Questions
- JSF Interview Questions
- JSP Interview Questions
- JPA Interview Questions
- Spring Framework Interview Questions
- Spring Boot Interview Questions
- Core Java Multiple Choice Questions
- 60 Java MCQ Questions And Answers
- Aricent Java Interview Questions
- Accenture Java Interview Questions
- Advanced Java Interview Questions For 5 8 10 Years Experienced
- Core Java Interview Questions For Experienced
- GIT Interview Questions And Answers
- Network Security Interview Questions
- CheckPoint Interview Questions
- Page Object Model Interview Questions
- Apache Pig Interview Questions
- Python Interview Questions And Answers
- Peoplesoft Integration Broker Interview Questions
- PeopleSoft Application Engine Interview Questions