Java Programming Interview Questions

Top 25 Java Programming Interview Questions and Answers

When people hear the word “art” they generally relate to literature, music, and paintings but there is more to it. Art is all about expressing your emotions, imaginations, thoughts, and ideas in an innovative way. Coding is also an art because coder goes through a different creative phase to solve a problem.

For a non-programmer, it may seem that programming is an easy task as they only have to map a real-world entity to objects or logic but it’s not simple like that. They have to come up with some creative ideas to solve the complex problem by taking in various constraints into consideration.

Coding is a necessary part of any programming job interviews and as Java being one of the most popular programming languages, there would be no exception. The market is also filled with computer graduates who are looking for jobs in java as coder or software developer. Tech giants like Google, Facebook, Microsoft, Amazon etc. like to test coding skills of any programmers they want to hire.  These interviews are tough to crack if you don’t have good programming skills.

Java Programming Interviews Questions and Answers

If you don’t have good coding skills, the most important question is how to develop it to get a place in a good IT company? The easiest and simplest thing will be to do is start small and write the programs and try to understand the logic behind it. Just pay attention and you will find many Java Programming Interviews Questions where you can find different coding related questions and answers.

These Java Programming Interviews Questions will give you enough indication about the coding skills and candidates are needed to getting hired. In this article, we will try to share some common Java coding interview questions which will really help you in your preparation. The more you practice these questions the more you will confident about your preparation.

Now without making any another delay, let’s take a look at most frequently asked java programming interview questions for freshers.

Q.1) Write a simple program to print Fibonacci series?

Fibonacci series is a sequence of numbers where the next value in the sequence is the sum of the previous two numbers.

Fibonacci series complete Java program

package com.javaquestions;

public class Fibonacci {

public static void main(String[] args) {

System.out.println(“Fibonacci(5)  =” + fibonacci(5));

}

public static int fibonacci(int n) {

if(n<0)

throw new IllegalArgumentException(“n should be positive integer”);

else if(n==0)

return 0;

else if(n==1)

return 1;

else

return (fibonacci (n-1) + fibonacci (n-2));

}

}

Q.2) Write a program to check if a number is prime or not?

A number is said to be a prime number which is only divisible by 1 or itself.

Prime number complete Java program

package com.javaquestions;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner (System.in);

Int number = Integer.Max VALUE:

System.out.println(“Enter the number to check if it is prime or not”);

while (number ! = 0)) {

number = sc.nextInt();

System.out.println(“Is it %d is prime? %s %s %s %n”, number, isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));

}

}

public static boolen isPrime(int number) {

int sqrt = (int) Math.sqrt(number) + 1;

if (number % I ==  0) {

return false;

}

}

return true;

}

Q.3) Write a program to check if a number is Armstrong or not?

A number is an Armstrong number if it equals to the cube of its all digit.

Ex- 153 is an Armstrong number because cube of its all digit is equal to the whole number.

1^3 + 5^3 + 3^3 = 153

Armstrong number complete Java program

package com.javaquestions;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

int num, rem, sum =0;

Scanner sc = new Scanner (System.in);

System.out.println(“Enter a number ”);

num=sc.nextInt();

for (int i = num; i > 0; i = i/10)

{

rem = i %10;

sum = sum + rem * rem * rem;

}

If (sum== num)

{

System.out.println(“Number is Armstrong number”);

}

else

{

System.out.println(“Number is not Armstrong number”);

}

}

}

Q.4) Write a program to check if a number is Palindrome or not?

A number is said to be palindrome when a number is equal to reverse of itself.

Ex- 121 is a palindrome number because the reverse of 121 is 121.

Palindrome number complete Java program

package com.javaquestions;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

System.out.println(“Enter a number”);

int palindrome = new Scanner (System.in).nextInt();

if (isPalindrome(palindrome)) {

System.out.println(“Number is Palindrome”);

}

else {

System.out.println(“Number is not Palindrome”);

}

}

public static boolean isPalindrome (int number) {

int palindrome = number;

int rev = 0;

while (palindrome ! = 0) {

int rem = palindrome % 10;

rev = rev * 10 + rem;

palindrome = palindrome / 10;

}

if (number == rev) {

return true;

}

return false;

}

}

Q.5) Write a program to check if a string is Palindrome or not?

package com.javaquestions;

import java.util.Scanner;

class ChkPalindrome

{

public static void main(String[] args)

{

String str, rev = "";

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");

str = sc.nextInt();

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )

rev = rev + str.charAt(i);

if (str.equals(rev))

System.out.println("String is a palindrome");

else

System.out.println(“String is not a palindrome");

}

}

Q.6) Write a program to calculate a factorial using recursion in Java?

Recursion is a process in which a function calls itself multiple times directly or indirectly. It is used where a logic needs to be executed multiple times.

Factorial of a number, a number n is expressed as n! and calculated as:

n! = n * (n-1) * (n-2)…. *2 * 1

Factorial complete Java program

package com.javaquestions;

public class Factorial {

public static void main(String[] args ) {

System.out.println (“6! =” + factorial (5));

}

private static long factorial(int num) {

if (num==1)

return 1;

else

return num * factorial(num-1);

}

}

Q.7) Write a program in java to Reverse a string?

Reverse of String complete Java program

package com.javaquestions;

import java.lang.*;

import java.io.*;

import java.util.*;

class ReverseString  {

public static void main(String[] args) {

String input = "Java Example";

char[] temparray = input.toCharArray();

int left, right=0;

right = temparray.length-1;

for (left=0; left < right ; left++ ,right--)  {

char temp = temparray[left];

temparray[left] = temparray[right];

temparray[right]=temp;

}

for (char c: temporary)

System.out.println(c);

System.out.println();

}

}

Q.8) Write a program in java to print Pyramid pattern?

Pyramid Pattern complete Java program

package com.javaquestions;

public class PyramidPattern {

public static void main(String args[]) {

int i, j, k=1;

for(i=0; i<5; i++) {

for(j=0; j<k; j++)  {

System.out.println("* ");

}

k = k + 2;

System.out.println();

}

}

}

Q.9) Write a program in Java to find the square root?

Square root complete Java program

package com.javaquestions;

import java.util.Scanner;

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);



System.out.println("Enter number to find square root in Java : ");

double square = scanner.nextDouble();

double squareRoot = Math.sqrt(square);

System.out.println("Square root of number: %f is : %f %n" , square, squareRoot);

}
  
}

Q.10) Write a program in Java to check if two string is an anagram or not?

Two words are said to be anagrams if the same set of characters are present in both of the words. For example, the word world can be re-arranged in dorlw and both words have the same characters and form an anagram.

Anagram complete Java program

package com.javaquestions;

public class StringAnagram {

public static void main(String[] args) {

String word="world";

String anagram="dorlw";

System.out.println("world and dorlw are anagrams :"+ isAnagramUsingStringMethods(word, anagram));

}

public static boolean isAnagramUsingStringMethods(String word,String anagram) {

if(word.length()!=anagram.length())

return false;

for (int i = 0; i < word.length(); i++) {

char c=word.charAt(i);

int index=anagram.indexOf(c);

if(index !=-1 0{

anagram=anagram.substring(0,index)+anagram.substring(index+1,anagram.length());

}

Else

return false;

}

return anagram.isEmpty();

}

}

Q.11) Write a program in Java to implement insertion sort?

Insertion Sort complete Java program

package com.javaquestions;

import java.util.Scanner;

public class Insertion {

public static void main(String args[])  {

int size, i, j, temp;

int arr[] = new int[10];

Scanner sc = new Scanner(System.in);

System.out.println("Enter Array Size : ");

size = scan.nextInt();

System.out.println("Enter Array Elements : ");

for(i=0; i<size; i++)  {

arr[i] = scan.nextInt();

}

System.out.println("Sorting Array using Insertion Sort Technique..\n");

for(i=1; i<size; i++) {

temp = arr[i];

j = i - 1;

while((temp < arr[j]) && (j >= 0) {

arr[j+1] = arr[j];

j = j - 1;

}

arr[j+1] = temp;

}

System.out.print("Array after Sorting is : \n");

for(i=0; i<size; i++)

{

System.out.println(arr[i] + "  ");

}

}

}

Q.12) Write a program in Java to implement bubble sort?

Bubble Sort complete Java program

package com.javaquestions;

import java.util.Scanner;

class Bubble {

public static void main(String []args) {

int n, c, d, swap;

Scanner sc = new Scanner(System.in);

System.out.println("Input number of integers to sort");

n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

for (c = 0; c < ( n - 1 ); c++) {

for (d = 0; d < n - c - 1; d++) {

if (array[d] > array[d+1])     {

swap       = array[d];

array[d]   = array[d+1];

array[d+1] = swap;

}

}

}

System.out.println("Sorted list of numbers:");

for (c = 0; c < n; c++)

System.out.println(array[c]);

}

}

Q.13) Write a program in Java to implement selection sort?

Selection Sort complete Java program

package com.javaquestions;

public class Selection {

public static void main(String []args) {

int [] num= {4,7,9,1,6,10,2,3,8,5};

int n= num.length;

selectionsort(num, 0, n -1);

for(int I =0; I <n; i++)

System.out.println(num[i]  + “ ”);

}

public static void selectionsort(int [] num, int low, int high)  {

for(int h =low; h<=high; h++)

swap(num, h, getSmallest(num, h, high));

}

public static void getSmallest(int [] num, int low, int high)  {

int small=low;

for(int i =low1; i<=high; i++)

if(num[i] < num[small])

small=i;

return small;

}

public static swap(int [] num, int i, int j)  {

int temp=num[i];

num[i]=num[j];

num[j]=temp;

}

}

Q.14) Write a program in Java to print all permutations of string?

Permutations of string complete Java program

package com.javaquestions;

Public class Permutations {

private static void swap (char[], ch, int I, int j)

char temp = ch[i];

ch[i] = ch[j];

ch[j] = temp;

}

private static void permutations(char[], ch, int currentIndex)  {

if(currentIndex == ch.length-1) {

System.out.println(String.valueOf(ch));

}

for(int i = currentIndex; i<ch.length; i++)  {

swap(ch, currentIndex, i);

permutations(ch, currentIndex + 1);

swap(ch, currentIndex, i);

}

}

public static void main(String[] args) {

String str = “JAVA”;

Permutations(str.toCharArray(), 0) ;

}

}

Q.15) Write a program in Java to implement Binary Search?

Binary search complete Java program

package com.javaquestions;

import java.util.Scanner;

class BinarySearch {

public static void main(String args[]) {

int c, first, last, middle, n, search, array[];

Scanner sc = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

first  = 0;

last   = n - 1;

middle = (first + last)/2;

while( first <= last ) {

if ( array[middle] < search )

first = middle + 1;

else if ( array[middle] == search ) {

System.out.println(search + " found at location " + (middle + 1) + ".");

break;

}

else

last = middle – 1;

middle = (first + last)/2;

}

if (first > last)

System.out.println(search + " isn't present in the list.\n");

}

}

Java programming questions for experienced professionals

In this section, we are going to talk about the Java programming questions for experienced professionals which will definitely help any professional who is eyeing to climb the ladder of success. These are the latest java programming interview question which will really strengthen your preparation.

Q.16) Write a program in Java to find the length of a linked list?

Linked list complete Java program

package com.javaquestions;

public class Node {

int data;

Node next;

Node(int d) {

data=d;

next=null;

}

}

Public class LinkedList {

Node head;

public void push(int new_data)  {

Node new_node= new Node(new_data);

new_node.next= head;

head= new_node;

}

public int getCountRec(Node node)  {

if(node==null)

return 0;

}

public int getCount()  { 

return getCountRec(head)’

}

public static void main(String[] args)  {

LinkedList list= new LinkedList();

list.push(1);

list.push(3);

list.push(1);

list.push(2);

list.push(1);

System.out.println(“Counts of nodes is ” + list.getCount());

}

}

Q.17) Write a program in Java to find the matric multiplication?

Matric multiplication complete Java program

package com.javaquestions;

import java.util.Scanner;

        class MatrixMultiplication  {

         public static void main(String args[]) {

        int m, n, p, q, sum = 0, c, d, k;

        Scanner sc = 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");

          }

         }

        }

Q.18) Write a program in Java to merging to sorted linked lists?

Merging to sorted linked lists complete Java program

package com.javaquestions;

public class ListMerge {

private static class Node {

private int data;

Node next;

public Node(int data) {

this.data = data;

next = null;

}

}

Node head;  

public static void main(String[] args) {

ListMerge list = new ListMerge();      

int[] data1 = { 10, 30, 50, 70 };

Node head1 = new Node(data1[0]);          

for (int i = 1; i < data1.length; i++)   

list.push(head1, data1[i]);

System.out.println("First List : ");

list.display(head1);

int[] data2 = { 20, 40, 60, 80 };

Node head2 = new Node(data2[0]);

for (int count = 1; count < data2.length; count++)

list.push(head2, data2[count]);

System.out.println("Second List : ");

list.display(head2);

Node n = list.mergeSortedLists(head1, head2);

System.out.println("Merged List : ");

list.display(n);

}

public Node mergeSortedLists(Node first, Node second) {

Node head;

if (first == null)

return second;

else if (second == null)

return first;

else if (first.data < second.data) {

head = first;

head.next = mergeSortedLists(first.next, second);     

}

else {

head = second;

head.next = mergeSortedLists(first, second.next);

}

return head;

}

public void push(Node head, int n) {     

while (head.next != null)

head = head.next;

head.next = new Node(n);

}

public void display(Node head) {

Node tempDisplay = head;

while (tempDisplay != null) {

System.out.println(tempDisplay.data);

tempDisplay = tempDisplay.next;

}

}

}

Q.19) Write a program in Java to detect a cycle in a singly linked list?

Detection of cycle in a singly linked list complete Java program

package com.javaquestions;

public class LinkedList {

private static class Node {

private int data;

Node next;

public Node(int data) {

this.data = data;

next = null;

}

}

Node head;

public static void main(String[] args) {

LinkedList list = new LinkedList();

list.push(10);

list.push(20);

list.push(30);

list.push(40);

list.createCycle();    

System.out.println("Checking for loop in the LinkedList returned " + list.detectCycle());

}

private boolean detectCycle() {     

Node lag = head;

Node lead = head.next;

while (lead.next != null) {         

if (lag == lead)

return true;

lag = lag.next;

for (int i = 0; i < 2; i++) {            

if (lead.next == null)

return false;

lead = lead.next;

}      

}       

return false;

}

public void push(int n) {

Node p = new Node(n);

p.next = head;

head = p;

}

public void createCycle() {

Node cur = head;

while (cur.next != null)

cur = cur.next;

cur.next = head;

}

}

Q.20) Write a program in Java to implement iterative quicksort?

Iterative Quicksort complete Java program

package com.javaquestions;

import java.util.Arrays;

import java.util.Scanner;

import java.util.Stack;

public class Sorting {

public static void main(String args[]) {

int[] unsorted = {34, 32, 43, 12, 11, 32, 22, 21, 32};

System.out.println("Unsorted array : " + Arrays.toString(unsorted));

iterativeQsort(unsorted);

System.out.println("Sorted array : " + Arrays.toString(unsorted));

}

public static void iterativeQsort(int[] numbers) {

Stack stack = new Stack();

stack.push(0);

stack.push(numbers.length);

while (!stack.isEmpty()) {

int end = stack.pop();

int start = stack.pop();

if (end - start < 2) {

continue;

}

int p = start + ((end - start) / 2);

p = partition(numbers, p, start, end);

stack.push(p + 1);

stack.push(end);

stack.push(start);

stack.push(p);

}

}

private static int partition(int[] input, int position, int start, int end) {

int l = start;

int h = end - 2;

int piv = input[position];

swap(input, position, end - 1);

while (l < h) {

if (input[l] < piv) {

l++;

 }

else if (input[h] >= piv) {

h--;

}

else {

swap(input, l, h);

}

}

int idx = h;

if (input[h] < piv) {

idx++;

}

swap(input, end - 1, idx);

return idx;

}

private static void swap(int[] arr, int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

}

}

Q.21) Write a program in Java to find the middle element of a Linked list?

Finding the middle element of a linked list complete Java program

package com.javaquestions;

import test.LinkedList.Node;

public class LinkedListTest {

public static void main(String args[]) {     

LinkedList linkedList = new LinkedList();     

LinkedList.Node head = linkedList.head();    

linkedList.add( new LinkedList.Node("1"));    

linkedList.add( new LinkedList.Node("2"));     

linkedList.add( new LinkedList.Node("3"));    

linkedList.add( new LinkedList.Node("4"));  

LinkedList.Node current = head;    

int length = 0;     

LinkedList.Node middle = head; 

while(current.next() != null){        

length++;         

if(length%2 ==0){            

middle = middle.next();         

}        

current = current.next();     

} 

if(length%2 == 1){       

middle = middle.next();     

}

System.out.println("length of LinkedList: " + length);     

System.out.println("middle element of LinkedList : " + middle);     

}   

}

class LinkedList{   

private Node head;   

private Node tail; 

public LinkedList(){       

this.head = new Node("head");     

tail = head;  

} 

public Node head(){       

return head;   

}

public void add(Node node){       

tail.next = node;      

tail = node; 

}

public static class Node{       

private Node next;      

private String data;

public Node(String data){           

this.data = data;       

}     

public String data() {          

return data;       

}

public void setData(String data) {           

this.data = data;       

}

public Node next() {           

return next;       

}

public void setNext(Node next) {           

this.next = next;      

}       

public String toString(){         

return this.data;

}   

}

}

Q.22) Write a program in Java to make a calculator?

Calculator complete Java program

package com.javaquestions;

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

double num1, num2;    

Scanner sc = new Scanner(System.in);      

System.out.println("Enter first number:");

num1 = scanner.nextDouble();       

System.out.println("Enter second number:");     

num2 = scanner.nextDouble();

System.out.println("Enter an operator (+, -, *, /): ");      

char operator = scanner.next().charAt(0);

scanner.close();      

double output;

switch(operator)       

{

case '+':                 

output = num1 + num2;               

break;

case '-':

output = num1 - num2;               

break;           

case '*':                 

output = num1 * num2;             

break;

case '/':        

output = num1 / num2;              

break;

default:               

System.out.println("You have entered wrong operator");              

return;       

}

System.out.println(num1+" "+operator+" "+num2+": "+output);  

}

}

Q.23) Write a program in Java to implement transpose of a matrix?

Transpose of a matrix complete Java program

package com.javaquestions;

import java.util.Scanner;

class TransposeAMatrix {  

public static void main(String args[]) {    

int m, n, c, d;    

Scanner sc = new Scanner(System.in);     

System.out.println("Enter the number of rows and columns of matrix");     

m = in.nextInt();     

n = in.nextInt();

int matrix[][] = new int[m][n];    

System.out.println("Enter the elements of matrix");

for (c = 0; c < m; c++)       

for (d = 0; d < n; d++)           

matrix[c][d] = in.nextInt();

int transpose[][] = new int[n][m];   

for (c = 0; c < m; c++)        

for (d = 0; d < n; d++)                          

transpose[d][c] = matrix[c][d];

System.out.println("Transpose of the matrix:");

for (c = 0; c < n; c++) {        

for (d = 0; d < m; d++)             

System.out.println(transpose[c][d]+"\t")

System.out.println("\n");     

} 

}

}

Q.24) Write a program in Java to implement inverse of a matrix?

Inverse of a matrix complete Java program

package com.javaquestions;

import java.util.Scanner;

public class JavaMatrixInverse {    

public static void main(String args[]                               

int i, j;                    

float det = 0;                        

float mat[][] = new float[3][3];        

Scanner sc = new Scanner(System.in);                           

System.out.println("Enter elements of matrix row wise:");                        

for(i = 0; i < 3; ++i)                                             

for(j = 0; j < 3; ++j)                                                            

mat[i][j] = sc.nextFloat();                  

for(i = 0; i < 3; i++)                     

det = det + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));                               

System.out.println("\ndeterminant = " + det);                                                               

System.out.println("\nInverse of matrix is:");

for(i = 0; i < 3; ++i) {                                          

for(j = 0; j < 3; ++j)                                                            

System.out.print((((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ det) + " ");                                               

System.out.print("\n");                      

}             

}

}

Q.25) Write a program in Java to implement Bucket sort?

Bucket Sort complete Java program

import java.util.*;

public class BucketSort{

public static void sort(int[] a, int maxVal) {     

int [] bucket=new int[maxVal+1];

for (int i=0; i<bucket.length; i++) {        

bucket[i]=0;    

}

for (int i=0; i<a.length; i++) {        

bucket[a[i]]++;     

}

int outPos=0;     

for (int i=0; i<bucket.length; i++) {       

for (int j=0; j<bucket[i]; j++) {           

a[outPos++]=i;       

}     

}  

}

public static void main(String[] args) {     

int maxVal=5;    

int [] data= {5,3,0,2,4,1,0,5,2,3,1,4};     

System.out.println("Before: " + Arrays.toString(data));     

sort(data,maxVal);    

System.out.println("After:  " + Arrays.toString(data));

}

}

Conclusion

These are the top 25 Java programming interview questions. You can practice these questions and look for more questions in different java blogs and forums. These questions will not only help you do well in programming job interviews but you will get the idea of how to code and this will definitely help your coding skills and you will able to understand any programming language thoroughly.


Kunal Avatar

About the author



Useful Links

Links I found useful and wanted to share.


Search the website