Top 30 Java Interview Programs


1. Program to reverse a String in Java .

2. Program to print Fibonacci series in java.

3.Program to print Fibonacci series in java using recursive method .

4.Program in java to find a String in a sentence.

5. Program to count no.of times a word repeats in String in Java

6. Program to find Prime number in java

7. Program to remove a particular character from a sentence

8. Count the Number of Vowels in Java String

9. Find the substring count from a string without string functions in java

10. Program in java to split String without using split() method

11. Program in java to check whether a String is palindrome or not

12. Program to find largest and smallest numbers among N numbers using an array

13 . How to remove duplicate characters from String in Java.

14. Program for Shifting character in a String eg. String "abcde" should be printed as "eabcd"

15. Program to find  Position of a String in another String.

16. How to sort and reverse an array list without using sort method

17. How to find first non-repeated character of a string in Java.

18. Bubble Sort in Java

19. How to find duplicate numbers in list in Java (using Collection)

20. How to Print numbers for 1 to 100 without using for Loop

21. Java program to find smallest substring in specified characters

22. Write a program to find out all possible unique subString present in a given string

23. How To Count Occurrences Of Each Character In String In Java

24. How to reverse a String using recursion

25. Equilibrium index of an array

26. Java Program to print numbers in pyramid shape

27. Java Program To Remove Duplicate Elements From ArrayList without using Collections

28. Java Program To find factorial of a number .

29. Java Program to find two highest number in an array 

30. How to remove duplicate characters from String in Java.

Find top two highest numbers in a array java


  • Hi Friends today we will discuss about how to find top two maximum numbers in an array using java program.
  • For this we have written separate function to perform logic
  • findTwoMaxNumbers method takes integer  array as an argument
  • Initially take two variables to find top to numbers and assign to zero.
  • By using for each loop iterating array and compare current value with these values
  • If our value is less than current array value then assign current value to max1 
  • And assign maxone to maxtwo because maxtwo should be second highest.
  • After completion of all iterations maxone will have top value and maxtwo will have second maximum value.
  • Print first maximum and second maximum values.
  • So from main method create array and pass to findTwoMaxNumbers(int [] ar)



package com.javainhouse;


public class FindTopTwo { public void findTwoMaxNumbers(int[] array){ int maxOne = 0; int maxTwo = 0; for(int i:array){ if(maxOne < i){ maxTwo = maxOne; maxOne =i; } else if(maxTwo < i){ maxTwo = i; } } System.out.println("First Maximum Number: "+maxOne); System.out.println("Second Maximum Number: "+maxTwo); } public static void main(String a[]){ int num[] = {4,23,67,1,76,1,98,13}; FindTopTwo obj = new FindTopTwo(); obj.findTwoMaxNumbers(num); obj.findTwoMaxNumbers(new int[]{4,5,6,90,1}); }

Output:




First Maximum Number: 98
Second Maximum Number: 76
First Maximum Number: 90
Second Maximum Number: 6

Finding Factorial of a number in Java

  • This interview question is mainly asked to freshers in Java Interviews.  
  • It also represents an example of recursion.
  • Factorial number means multiplication of all positive integer from one to that number.
  • Two factorial:   2!=  2*1=2
  • Three factorial: 3!= 3*2*1=6.
  • Eight factorial:   8!= 8* 7*6*5*4*3*2*1=40320



where ' ! ' sign represents the factorial .


package com.javainhouse;

import java.util.Scanner; public class FactiorialProgram { public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Enter a number to find factorial"); int n= in.nextInt(); int fact=1; for (int i = 1; i < n; i++) { fact=fact*i; } System.out.println("Factorial of "+n+" is "+fact); } }



Output:

Enter a number to find factorial
5
Factorial of 5 is 24

Java Program To Remove Duplicate Elements From ArrayList without using Collections



package com.javainhouse;

import java.util.ArrayList; 
public class RemoveDuplicates {
public static void main(String[] args)
{

 ArrayList<Object> al = new ArrayList<Object>(); 
 al.add("java"); 
 al.add('a');
 al.add('b');
 al.add('a');
 al.add("java");
 al.add(10.3); 
 al.add('c'); 
 al.add(14); 
 al.add("java"); 
 
 al.add(12); 
 System.out.println("Before Remove Duplicate elements:"+al);

 for(int i=0;i<al.size();i++)
 { 
 
for(int j=i+1;j<al.size();j++)
if(al.get(i).equals(al.get(j)))
al.remove(j); j--; 
System.out.println("After Removing duplicate elements:"+al);
}
}

Java Program to print numbers in pyramid shape


package com.javainhouse;

public static void main(String[] args)
 {
  
   
   int test=5;
   
   for (int i=1;i<test;i++)
   {
     int j=1;
     
      for ( j=1;j<i;j++)
    {
        
         System.out.print(j);
      }
     
      for (int k=j;k>0;k--)
    {
        
         System.out.print(k);
      }
     System.out.println();
   }
   
  
 }


OutPut: 


1
121
12321
1234321


25 Java Interview Questions

1. Program to reverse a String in Java .

2. Program to print Fibonacci series in java.

3.Program to print Fibonacci series in java using recursive method .

4.Program in java to find a String in a sentence.

5. Program to count no.of times a word repeats in String in Java

6. Program to find Prime number in java

7. Program to remove a particular character from a sentence

8. Count the Number of Vowels in Java String

9. Find the substring count from a string without string functions in java

10. Program in java to split String without using split() method

11. Program in java to check whether a String is palindrome or not

12. Program to find largest and smallest numbers among N numbers using an array

13 . How to remove duplicate characters from String in Java.

14. Program for Shifting character in a String eg. String "abcde" should be printed as "eabcd"

15. Program to find  Position of a String in another String.

16. How to sort and reverse an array list without using sort method

17. How to find first non-repeated character of a string in Java.

18. Bubble Sort in Java

19. How to find duplicate numbers in list in Java (using Collection)

20. How to Print numbers for 1 to 100 without using for Loop

21. Java program to find smallest substring in specified characters

22. Write a program to find out all possible unique subString present in a given string

23. How To Count Occurrences Of Each Character In String In Java

24. How to reverse a String using recursion



How To Count Occurrences Of Each Character In String In Java?



import java.util.HashMap;

public class CountCharInStringJavaInHouse
{
  
   public static void main(String[] args)
    {
       countCharacter("How many number each character is there in string using hashmap");
    }
    static void countCharacter(String inputString)
    {
        
        HashMap<Character, Integer> resultMap = new HashMap<Character, Integer>();
        
        char[] strArray = inputString.toCharArray();

        for (char c : strArray)
        {
          
          if(resultMap.containsKey(c) )
            {

                resultMap.put(c, resultMap.get(c)+1);
            }
            else
            {


                resultMap.put(c, 1);
            }
          
        }

        System.out.println(resultMap);
    }
   
}

OutPut:
Occurrences Of Each Character In String

How to reverse a String using recursion

For the solution of this program we will use recursion mechanism in which a method calls itself again and again till the condition satisfies.





package com.javainhouse;


public class reverseString

 { String reverse = "";
public String reverseString(String str)
{

if(str.length() == 1)
{
return str;
}

else

{
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}

}

public static void main(String a[])

{
StringRecursiveReversal srr = new StringRecursiveReversal();
System.out.println("Result: "+srr.reverseString("Java2novice"));

}
 } 



Output:

Reverse String Java




20 Java Programs to clear Java Interview

How to Print numbers for 1 to 100 without using for Loop

This is very common interview question asked in java interviews .It can be asked in other way also as an example of recursion .

For the solution of this program we will use recursion mechanism in which a method calls itself again and again till the condition satisfies.





package com.javainhouse;


public class JavaInHousePrintNumber
{
  
  public static void main(String[] args)
  {
    printNumber(100);
    
  }



public static void printNumber(int number)
{
  if(number>0)
  {
    
    
    System.out.print(" "+number);
    number--;
    printNumber(number);
  }
  
}

}

     



Output:

Print Numbers Java

How to Find duplicate numbers in given list in Java

For this program we are going to use HashSet as Set does not allow duplicate elements.

We will be using two HashSets . As he list is traversed ,all the elements will be started storing in the first hash set and if any element is traversed again the first hash set will not allow that element and that element will be stored in the second hash set and at last we ll print the second Hash set .




package com.javainhouse;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class findDuplicateElements
{

public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
for (int i = 2; i < 7; i++) {
list.add(String.valueOf(i));
}
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
 
for (String element : list) {
if (!set1.add(element)) {
setToReturn.add(element);
}
}
 
System.out.println("Original List : " + list);
System.out.println("Duplicate elements from list : " + setToReturn);
}
 
}
     

OutPut :

Duplicate Elements in List Program



Bubble Sort in Java

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
                                    First Pass:
                                    ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps                                                                                      since 5 > 1.
                                    ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
                                    ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
                                    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ),  
                                   Second Pass:
                                 ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
                                 ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
                                 ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                 ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs onewhole pass without any swap to know it is sorted.
                                 Third Pass:
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

package com.javainhouse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


        
public class MyBubbleSortJavainHouse {
 
    public static void main(String[] args) {
        int[] array = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        int n = array.length;
        int k;
        for (int i = 0; i < n ; i++)
            {
            for (int j = 0; j < n -1; j++)
            {
                k = j + 1;
                if (array[j] > array[k])
                {
                 int temp;
              temp = array[j];
              array[j] = array[k];
              array[k] = temp;
                }
            }
            
            }
            
        for (int m = 0; m < array.length; m++) {
            System.out.print(array[m] + ", ");
        }
        System.out.println("\n");
   
 
    }
}

Output :
Bubble Sort Java


How to create a custom exception in Java


Why we need custom Exception ?
How to create a custom exception ?
Write code to create a Custom Exception

All these are questions usually asked in a Java interview .So my today's post on how to create a custom exception in java .

As we know There are two types of Exception :
1. Checked Exception
2. Unchecked Exception

Both these exceptions have a common parent class Exception .So ,in same order if we have to create a custom exception ,we need to extend Exception class.

Ok , let me explain the process step by step .

1. Any custom exception should extend Exception Class .

2. There should be a proper name given to the Exception ,For example if there is an exception related to Invalid age name can be given as InvalidAgeException


public class InvalidAgeException extends Exception {}


public class InvalidAgeException extends Exception {
private int age;

public InvalidAgeException ()
{
super();
}
public InvalidAgeException (String message, int age)

{
   super(message);

   this.age = age;


}

In the above way we can define two constructors of InvalidAgeException with message and without message

Usage of custom Exception:

Below is the program with usage of custom exception.

public class CustomExceptionDemo 



private static final Map<Integer, String> employee = new HashMap<>(); 

static

 {
   employee.put(100"Mahesh");
  employee.put(101"Suresh");

   employee.put(102"Bran");

   employee.put(103"Troy"); }

 public static void main(String args[])
 { 

     CustomExceptionDemo t = new CustomExceptionDemo();

    t.getAge(1000); } 

public String getAge(int age)

 { 

     if (employee.get(age) == null)


   throw new InvalidAgeException ("No such employee exists", age);

return employee.get(name);

}

}