Top 20 Java Coding Interview Questions

In This tutorial, I have tried to provide commonly asked Java coding interview questions and answers.

1) How do you reverse a string in Java using all possible ways?

1)By Using String Buffer

In Java, StringBuffer is a class that represents a mutable sequence of characters. This is synchronized and thread-safe hence suitable for string modification.

public class ReverseString {

    public static void main(String[] args) {

        StringReverse("automationqahub");

    }
    public static void StringReverse(String str) {

        StringBuffer bf = new StringBuffer(str);
        System.out.println(bf.reverse());


    }

}

2)Converting string to a character array.

public class ReverseString {

    public static void main(String[] args) {

        StringReverse("automationqahub");

    }
    public static void StringReverse(String str) {
        char ar[] = str.toCharArray();
        for (int i = str.length() - 1; i >= 0; i--) {
            System.out.print(ar[i]);
        }

    }

}

3)By Using Recursion

public class ReverseString {

    public static void main(String[] args) {

        StringReverseusingRecursion("automationqahub");
    }
    public static void StringReverseusingRecursion(String str) {
        if ((str == null) || (str.length() <= 1))
            System.out.println(str);
        else {
            System.out.print(str.charAt(str.length() - 1));
            StringReverseusingRecursion(str.substring(0, str.length() - 1));
        }

    }

}

2) WAP to swap 2 numbers without using 3rd variable(Don’t use ‘+’ and ‘-‘ Operator).

1)Using Arithmetic Operators:

public class SwapNumber {

    public static void main(String[] args) {

        SwapNumbers(5, 7);

    }
    public static void SwapNumbers(int a, int b)

    {
        a = a * b;
        b = a / b;
        a = a / b;
        System.out.print("a:" + a + "b:" + b);
    }

}

2)Using Bitwise Operators

public class SwapNumber {

    public static void main(String[] args) {

        SwapNumbers(5, 7);

    }
    public static void SwapNumbers(int a, int b)

    {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.print("a:" + a + "b:" + b);
    }

}

3) WAP to find duplicate elements in an array with and without using the collection.

1)Using Collection

HashSet is a collection class that implements the Set interface. It ensures that it contains unique elements.

import java.util.HashSet;
import java.util.Set;

public class DuplicateElement {

	public static void main(String[] args) {
		
		int [] numarray= {5,2,4,0,1,2,5,7};
		FindDuplicateElements(numarray);

	}
	public static void FindDuplicateElements(int [] array)
  
	{    
		     
	      Set<Integer> dupnumber=new HashSet<>();
	      for(Integer number : array)
	      {
	    	  if(!dupnumber.add(number))
	    	  {
	    		  System.out.println("Duplicate elem is:"+number);
	    	  }
	      }
		
	}   

}

2)Without using the collection

 public static void dup()    
{
	 int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};   
	 System.out.println("Duplicate elements in given array: ");
         for(int i = 0; i < arr.length; i++) {
          for (int j = i + 1; j < arr.length; j++) {
             if (arr[i] == arr[j])
                 System.out.println(arr[j]);
         }
     }
}  

4) Write a program to count the frequency of elements in a string.


public class FrequencyCount {

    public static void main(String[] args) {
        Findrepeter();
    }


    static void Findrepeter() {
        String str = "aabrakaadaabratest";
        String[] strSplit = str.split("");
        ArrayList < String > strList = new ArrayList < String > (
            Arrays.asList(strSplit));

        Set < String > distinct = new HashSet < > (strList);
        for (String s: distinct) {
            System.out.println(s + ": " + Collections.frequency(strList, s));
        }

    }

}

5) Write a program to remove duplicate elements from an array.



public class RemoveDuplicate {

	public static void main(String[] args) {
		
		int [] numarray= {5,2,4,0,1,1,2,5,7};

		removeDuplicates(numarray);
		 public static void removeDuplicates(int[] a)
	    {
	        LinkedHashSet<Integer> set
	            = new LinkedHashSet<Integer>();
	  
	        
	        for (int i = 0; i < a.length; i++)
	            set.add(a[i]);
	  
	       
	        System.out.print(set);
	    }
	}
	 
}	

6) How to print the Fibonacci series using recursion?

public class ReverseString {

    public static void main(String[] str) {
        int n = 10;
        for (int i = 1; i <= n; i++) {
            System.out.println(fibonacciusingrecursion(i));

        }
    }
    static int fibonacciusingrecursion(int n) {
        if (n == 1)
            return 1;
        else if (n == 0)
            return 0;
        else
            return (fibonacciusingrecursion(n - 1) + fibonacciusingrecursion(n - 2));
    }
}

7) How do you print the date in a specific format in Java?

public static void main() {


    String pattern = "MM-dd-yyyy";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

    String date = simpleDateFormat.format(new Date());
    System.out.println(date);

}

8) Write a program to sort ArrayList in descending order.

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

        ArrayList < String > arraylist = new ArrayList < String > ();
        arraylist.add("India");
        arraylist.add("Nepal");
        arraylist.add("Newzeland");
        arraylist.add("Bhutan");


        System.out.println("ArrayList Before Sorting:");
        for (String str: arraylist) {
            System.out.println(str);
        }

        Collections.sort(arraylist, Collections.reverseOrder());

        System.out.println("ArrayList in descending order:");
        for (String str: arraylist) {
            System.out.println(str);
        }
    }
}

9) How to sort HashSet in Java?

By Using tree set we can sort Set in Java. The tree set by default sorts the elements in ascending order.

public static void sortSet() {

    HashSet < String > set = new HashSet < String > ();
    set.add("test");
    set.add("practice");
    set.add("contribute");
    set.add("ide");
    set.add("java");

    System.out.println("Original HashSet: " +
        set);

    TreeSet < String > treeSet = new TreeSet < String > (set);

    // Print the sorted elements of the HashSet
    System.out.println("HashSet elements " +
        "in sorted order " +
        "using TreeSet: " +
        treeSet);
}

10) How do you rotate the array by one position?

public class RotateArray {

    public static void main(String[] args) {

        int[] numarray = {
            7,
            5,
            1,
            0,
            9
        };

        LeftRotate(numarray);
        public static void LeftRotate(int[] array) {
            int temp = array[0];
            for (int i = 1; i < array.length; i++) {
                array[i - 1] = array[i];
            }
            array[array.length - 1] = temp;
            for (int i: array) {
                System.out.print(i);
            }

        }
    }

11) Find all divisors of a natural number in Java.

    public static void main(String[] args) {
        int num =45;
        int i=0;
        for(i=1;i*i <=num;i++)
        {
            if(num % i==0)
            {
                System.out.println(i); //first diviser
                if(i!=num/i)
                {
                   System.out.println(num/i);  //second diviser
                }
            }
        }
    }
}

12) Write a program to sort an Array using Insertion Sort.

package test;

import java.util.Arrays;

public class insertionsort {
      static int[] arr = {2,5,1,3,0,9}; 
	    static int temp;
	    
	    public static void main(String[] args) {
	        for(int i=1;i<arr.length;i++)
	        {
	            temp=arr[i];
	            int j=i;
	            while(j>0 && arr[j-1] > temp)
	            {
	                arr[j] = arr[j-1];
	                j=j-1;
	                
	            }
	            arr[j] = temp;
	        }
	        System.out.println("Sorted array is:"+Arrays.toString(arr));
	    }
	}

13) Write a program to find the complement of a number

Input-6(110)
Output-1(001)
import java.util.Scanner;

class sol1 {
	  
    public static void main(String args[])
    {
    	System.out.println("enter number");
    	
     try (Scanner inp = new Scanner(System.in)) {
			int number= inp.nextInt();
			int rem[]=new int[6];
			
			int i=0;
			while(number >0)
			{
				rem[i]=number%2;
				number=number/2;
				i++;
			}
			for(int j=i-1;j>=0;j--)
			{
				
				
				if(rem[j]==0)
				{
					System.out.print(1);
				}
				else
				{
					System.out.print(0);
				}
			}
		}
    }
}

14) WAP to fetch numerics from an alphanumeric string.

Use the IsDigit() method of Character Class. This is an inbuilt method that determines whether the specified char value is a digit or not.

public class isdigit {

public static void separate(String string) {

    StringBuilder alphabetsBuilder = new StringBuilder();
    StringBuilder numbersBuilder = new StringBuilder();
    
    for (int i = 0; i < string.length(); i++) {
        char ch = string.charAt(i);
        if (Character.isDigit(ch)) {
            numbersBuilder.append(ch);
        } 
        else {
            alphabetsBuilder.append(ch);
        }
    }
  
    System.out.println("Numbers in String: " + numbersBuilder.toString());
    }
    public static void main(String str[])
    {
     separate("Test4567");
     }
}

15) How to calculate max consecutive ones from a binary array?

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        
        int count=0;
        int max=0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]!=0)
            {
                count++;
                max=Math.max(max,count);
            }
            else
            {
                count=0;
            }
        }
        return max;
    }
}
class main
{
    static int num []={1,1,0,1,0,0,1,1,1};
    public static void main(String [] str)
    {
        Solution s = new Solution();
       int total= s.findMaxConsecutiveOnes(num);
        System.out.println(total);
    }
}

16) How to retrieve all the keys present in HashMap?

public class JavaHashMapExample 
{    
    public static void main(String[] args) 
    {
       
   HashMap<Integer, String> map = new HashMap<Integer, String>();
         
     map.put(1, "Test");
         
     map.put(2, "Java");
         
     map.put(3, "Program");
         
     map.put(4, "For");
         
     map.put(5, "Hashmap");
         
   Set<Integer> keySet = map.keySet();
         
        for (Integer key : keySet) 
        {
            System.out.println(key);
        }
    }   
}

17) How to Sort HashMap using keys?

import java.util.*;

class sortHashMap {

	static Map<String, Integer> map = new HashMap<>();

	public static void sortbykey() {
		ArrayList<String> sortedKeys = new ArrayList<String>(map.keySet());

		Collections.sort(sortedKeys);

		for (String x : sortedKeys)
			System.out.println("Key = " + x + ", Value = " + map.get(x));
	}

	public static void main(String args[]) {
		map.put("test", 80);
		map.put("hash", 90);
		map.put("map", 80);
		map.put("sorting", 75);
		map.put("injava", 40);

		sortbykey();
	}
}

18) Count the number of characters of the last word in a string.

public class leetcode {
	
	static int reverseEachWordOfString(String inputString)
    {
		int len=0;
        String x=inputString.trim();
        System.out.println(x);
      
         
        for (int i = 0; i < x.length(); i++) {
            if (x.charAt(i) == ' ')
                len = 0;
            else
                len++;
        }
 
        return len;
    }
 
     public static void main(String[] args) 
    {
        int count=reverseEachWordOfString("Count occurence of string ");
         
        System.out.print(count);
    }
}

19) Write a program to reverse an Array list in Java.

 public static void  reverseList()
    {
        List<Character> listb = new ArrayList<Character>();
    	
    	listb.add('a');
    	listb.add('b');
    	listb.add('z');
    	listb.add('c');
        for (int i = 0; i < listb.size(); i++) {
            listb.add(i, listb.remove(listb.size() - 1));
        }
        System.out.println(listb);
      }

20) Write a programme to split a string without using any inbuilt method.

public static void splitString()
    {
    	 Scanner input = new Scanner(System.in);
         System.out.print("Enter the String to be Spilted : ");
         String st = input.nextLine();
         Scanner str = new Scanner(st);
         while (str.hasNext())
         {
        	
             System.out.println(str.next());
         }
 }

For More coding questions visit Github Repository. To learn more interview questions related to test automation visit this section.

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading