Top 15 Java Programs for Interview with Explanation

Are you preparing for a Java programming interview? You’ve come to the right page. With a comprehensive collection of Java interview questions and answers, you’ll be fully prepared to tackle any question thrown your way.

From basic syntax to complex algorithms, we cover it all. Brush up on your Java skills and impress your interviewer with your knowledge and confidence. Whether you’re a beginner or an experienced programmer, this page is the perfect resource to help you ace your next Java interview.

15 Most asked Java Programs for Interview

Go through the top 15 Java Programs listed below and take the first step toward landing your dream software development job!

Q1. Write a Java Program to reverse a string without using the String inbuilt function.

public class ReverseString {

     public static void main(String[] args) {

          String str = "Avichal";
          StringBuilder str2 = new StringBuilder();
          str2.append(str);
          str2 = str2.reverse();     
          System.out.println(str2);

          }

}
Output: lahcivA

Explanation:

Here we initialize the string variable str and use the string builder class.

An object of string builder class str2 is further used to append the value stored in the string variable str.
It then uses the string builder’s built-in function (reverse()) to store the new reverse string in str2. Finally, print str2.

Q2. Java program to find a prime number?

import java.util.Scanner;

class Prime {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter a number to check if it is prime: ");
        int number= sc.nextInt();
        if(isPrime(number)) {
            System.out.println(number + " is prime number");
        }
        else{
            System.out.println(number + " is a non-prime number");
        }
    }
        static  boolean isPrime(int number)
    {
        if(number<=1)
        {
            return false;
        }
        for(int i=2;i<=number/2;i++)
       {
           if((number%i)==0)
               return  false;
       }
        return true;
    }}
Input: 7
Output: 7 is a prime number

Explanation:

Here the objective of our program is to check whether the given number is a prime number or not to check that we make a Boolean function if the number is less than or equal to one it returns false automatically as 1 and zero are not prime.

For a number greater than one, we run a loop till number/2 and check if a number is divisible by any number in the range we return false if it divisible else after the loop ends and we don’t find any number we return true as it does not have any divisor.

Q3. Java program to check if a number is a palindrome or not?

class Palindrome{  
   public static void main(String args[]){  
       int remainder ,sum=0, temp;    
       int n=502;
  
      temp=n;    
      while(n>0){    
      remainder=n%10;    
      sum=(sum*10)+remainder;    
      n=n/10;    
  }    
     if(temp==sum)    
     System.out.println("palindrome number ");    
  else    
    System.out.println("not palindrome");    
}  
} 
Ouput: not palindrome 

Explanation:

Here we initialize four variables n in which we store the original number remainder sum and temp we store the value of n in temp we start working on n now to obtain the last digit of the number n we use the mod operation and we start storing it as the first value in sum we generate the reverse of the number and store it in sum now we check if the original value of the number that was stored in temp is equal to the sum or not if it is equal we return palindrome number else, not a palindrome.

Q4. Java program to calculate the factorial of a number?

class Factorial{  
   public static void main(String args[]){  
       int i,fact=1;  
       int number=5;//It is the number to calculate factorial    
       for(i=1;i<=number;i++){    
       fact=fact*i;    
  }    
       System.out.println("Factorial  is: "+fact);
  }  
  }  
Output: Factorial is: 120

Explanation:

Here we take the number 5 whose factorial we need to find we take the initial value of the factorial as 1 and store it in a variable named fact. Now we run a loop from 1 to the number whose factorial we need to find and with each increment in the loop we update the value of fact as Fact=fact*i and this resulting value of the fact is the factorial of a given number.

Q5. Java program to swap two numbers using a temporary variable?

public class Swap {

    public static void main(String[] args) {

        float a = 1.20f, b = 2.45f;

        System.out.println("--Before swap--");
        System.out.println("First number = " + a);
        System.out.println("Second number = " + b);

        float temporary = a;
        a = b;
        b = temporary;

        System.out.println("--After swap--");
        System.out.println("First number = " + a);
        System.out.println("Second number = " + b);
    }
}
Output: 
--Before swap--
First number = 1.20
Second number = 2.45
--After swap--
First number = 2.45
Second number = 1.20

Explanation:

Here we take three variables two variables a and b to swap and one temporary variable what we do is we store the value of a in temporary now we give a value of b after this we give b the value of temporary which stores the value of a thus swapping the two variables.

Q6. Java program to find the Fibonacci series?

class Fibonacci{  
public static void main(String args[])  
{    
      int n1=0,n2=1,n3,i,count=10;    
      System.out.print(n1+" "+n2);
      for(i=2;i<count;++i)    
 {    
      n3=n1+n2;    
      System.out.print(" "+n3);    
           n1=n2;    
           n2=n3;    
 }    
  }}
Output: 0 1 1 2 3 5 8 13 21 34

Explanation:

Here we are trying to find the Fibonacci series we are finding the first 10 Fibonacci number the first is 0 and the second is one so it is printed by default after that we get the third by taking the sum of the first two and then we replace the value in n1 with n2 and the one in n2 with n3 to get the whole series.

Q7. Java program to find the HCF of two numbers?

import java.util.Scanner;
public class GCD {
      public static void main(String args[]){
          int first, second, i, gcd = 0;
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter first number :: ");
          first = sc.nextInt();
          System.out.println("Enter second number :: ");
          second = sc.nextInt();

          for(i = 1; i <= first || i <= second; i++) {
          if( first%i == 0 && second%i == 0 )
          gcd = i;
      }
          System.out.println("HCF of given two numbers is ::"+gcd);
   }
}
Input:
Enter first number: 4
Enter second number: 6


Output: HCF of given two number is: 2

Explanation:

We define two variables A and B and we loop from 1 to max of A and B we check if both are completely divided by a number in the loop if yes then we store that number in gcd and that stored number is displayed as the greatest common divisor.

Q8. Java program to swap two numbers without using a temporary variable?

import java.util.Scanner;
  
class SwapTwoNumber
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
  
      x = in.nextInt();
      y = in.nextInt();
  
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
  
      x = x + y;
      y = x - y;
      x = x - y;
  
      System.out.println("After Swapping without third variable\nx = "+x+"\ny = "+y);
   }
}
Input: Enter x and y
5 6

Output:
Before Swapping
x = 5
y = 6
After Swapping without third variable
x = 6
y = 5

Explanation:

X contains the sum of both x and y that is x+y then we assign y with the value of x-y which means we are subtracting y from x+y thus making the value of y as x now in the last step we assign x with the value x-y which means x=y.

Q9. Java program to iterate array list using for loop, while loop, advance for loop?

import java.util.*;
 
public class arrayList {
public static void main(String[] args) {
        ArrayList arr = new ArrayList();
        arr.add("15”);
        arr.add("25");
        arr.add("35");
        System.out.println("While Loop:");
        Iterator itr = arr.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
        System.out.println("Advanced For Loop:");
        for(Object obj : arr) {
            System.out.println(obj);
    }
        System.out.println("For Loop:");
        for(int i=0; i&lt;arr.size(); i++) {
            System.out.println(arr.get(i));
        }
}
}
Output:
While Loop:
15
25
35
Advanced For Loop:
15
25
35
For Loop:
15
25
35

Explanation:

Whenever the iterator has (next) element, it will display that element until we reach the end of the list. So it will iterate three times.

For advance for loop, an object is created for the array and this will iterate until the end of the array and will output all the elements of the array.

In the normal for loop we have a counter variable set as zero we put the condition for the loop to iterate till the end of the array each element is printed with the counter being increased each and every time.

Q10. Java program to find duplicates in a string?

public class Duplicate {
          
      public static void main(String[] args) {
           String str = new String("Avichall");
            int count = 0;
            char[] chars = str.toCharArray();
            System.out.println("Duplicate characters :");
            for (int i=0; i&lt;str.length();i++) {
                     for(int j=i+1; j&lt;str.length();j++) {
                     if (chars[i] == chars[j]) {
                                     System.out.println(chars[j]);
                                     count++;
                                     break;
                      }
                }
           }
     }
 
}
Output:
Duplitcate characters: l

Explanation:

We’ve generated the string variable str and initialised the integer count to 0 in this application.

In order to translate our string variable into a character, we then generated a character array. We are comparing various characters located at various indexes with the aid of a for a loop.

After each repetition, the number is increased by 1 if two consecutively indexed characters match. Otherwise, the character is printed.

Q11. Java program to find the third highest number in an array?

public class ThirdLargestInArrayExample{  
public static int getThirdLargest(int[] a, int total){  
       int temp;  
       for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[total-3];  
}  
      public static void main(String args[]){  
      int a[]={1,2,5,6,3,2};  
      int b[]={44,66,99,77,33,22,55};  
  System.out.println("Third Largest: "+getThirdLargest(a,6));  
  System.out.println("Third Largest: "+getThirdLargest(b,7));  
}}  
Output:
Third Largest: 3
Third Largest: 66

Explanation:

Here what we are doing is basically sorting the array and after sorting we return the third highest from the array.

Q12. Java program to check for Armstrong number of 3 digit?

public class Armstrong {
public static void main(String[] args) {

        int num = 425, temp, remainder, result = 0;
        temp = num;
        while (temp != 0)
        {
            remainder = temp % 10;
            result += Math.pow(remainder, 3);
            temp /= 10;
        }
        if(result == num)
            System.out.println(num + " is an Armstrong number.");
        else
            System.out.println(num + " is not an Armstrong number.");
    }
}
Output:
425 is not an Armstrong number.

Explanation:

Here we try to extract each digit from the given number that is num then after extracting the digit we take it with power 3 and add to result we do this till the number is !=0 if result==num it is an Armstrong number else it is not an Armstrong number.

Q13. Java program to remove all white spaces from a string using replace()?

class Remove
{
    public static void main(String[] args)
    {
        String str1 = "Saket Avichal        is a Engine    er";
        String ans = str1.replaceAll("\\s", "");
        System.out.println(ans);
  
           }
}
}
Output:
SaketAvichalisaEngineer

Explanation:

ans variable is initialized with replaceAll option to remove all the white spaces in str1 and the result is stored in the ans variable after that we print out that ans variable.

Q14. Java program to iterate hashmap using while and advance for loop

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class HashMapIteration {
 
    public static void main(String[] args) {
        HashMap&lt;Integer,String&gt; map = new HashMap&lt;Integer,String&gt;();
        map.put(2, "Saket");
        map.put(25, "Saurav");
        map.put(12, "HashMap");
        System.out.println(map.size());
        System.out.println("While Loop:");
        Iterator itr = map.entrySet().iterator();
        while(itr.hasNext()) {
            Map.Entry me = (Map.Entry) itr.next();
            System.out.println("Key is " + me.getKey() + " Value is " + me.getValue());
        }
        System.out.println("For Loop:");
        for(Map.Entry me2: map.entrySet()) {
            System.out.println("Key is: " + me2.getKey() + " Value is: " + me2.getValue());
        }
    }
 
}
Ouput:
Key is 2 Value is Saket
Key is 12 Value is Hashmap
Key is 25 Value is Saurav

Explanation:

Three elements have been added to this HashMap using the put() function.

The size() method can be used to determine the map’s size. After that, we iterated through the map, which has one key-value pair for each entry, using a while loop. GetKey() and getValue functions can be used to retrieve Keys and Values ().

Similar to this, we have a “me2” object for the hash map and have utilised an advanced for loop.

Q15. Java program to check the length of a linked list?

import java.io.*;
import java.util.LinkedList;
  
public class LinkedListDemo {
public static void main(String args[])
    {
        LinkedList<String> list = new LinkedList<String>();
  
        list.add("Hello");
        list.add("World");
        list.add("10");
        list.add("20");
  
        System.out.println("LinkedList:" + list);
        System.out.println("The size of the linked list is: " 
                                                + list.size());
    }
}
Ouput:
LinkedList: [“Hello”,“World”,10,20]
The size of the linked list is 4

Explanation:

Here we add the elements to the linkedlist using list.add after that there is an inbuilt method in java to get the size of linked list i.e. list.size()

Also Read:

Top 30 C Programming Interview Questions
Top 35 CSS Interview Questions

Leave a Comment