The Most Common Java Programming Interview Questions

Ankora Software Development
10 min readJun 25, 2020

--

Using these common interview questions, you can get a good sense of the candidate’s basic to high-level coding skills. To simplify things, we have grouped the problems into categories of string questions, number problems, and more abstract test questions.

String Questions

Count the Number of Words in a String

A basic but essential coding skill is to be able to parse out the words in a string. Ask this question to gauge the coding level of the Java developer. You can also specify that they use HashMap to solve the equation. One coding example might be:

public class CountStringpublic class CountString{static int i,c=0,res;static int wordcount(String s){char ch[]= new char[s.length()];for(i=0;i0)&&(ch[i]!=’ ‘)&&(ch[i-1]==’ ‘)) || ((ch[0]!=’ ‘)&&(i==0)) )c++;}return c;}public static void main (String args[]){res=StringDemo.wordcount(“ the blue bird flies south for the winter “);System.out.println(“The number of words in the string is : “+res);}}

The output is 8.

How to Reverse a String in Java

Another commonly used java programming interview question to ask the programmer is to write a Java program to reverse a string. To test the Java developer further, ask them to do it without using the reverse() method. There are multiple ways to reverse a string using a variable in Java, so they should know at least a few of them. One method to use is:

  1. Convert the input string into a character array by using the toCharArray() built-in method of the String Class.
  2. Scan the character array from both sides.
  3. Set the left index equal to 0 and right index equal to the length of the string -1.
  4. Swap the characters, of the start index scanning (one-by-one) with the last index scanning.
  5. Increase the left index by 1, and continue until the left side is less than or equal to the right.

How Do You Remove All the White Spaces in a String?

Ask the Java developer to remove all the white spaces in a string variable. This type of problem is a basic task, and any job candidate worth his or her salt should be able to code this one quickly. A quick example would be:

public class RemoveWhiteSpace{static int i;static void squeeze(String s){for(i=0;i

Check to See if a String is a Palindrome

A good developer will have no problem writing code testing to see if a string is a palindrome or not. To make the test more challenging, ask the interviewee to implement it without using any library method or subString(). A sample script to do this is:

import java.util.*;import java.lang.String;public class PalindromeTest{static Scanner console = new Scanner(System.in);public PalindromeTest(){}public static void main(String[] args){//declare the variablesString str,another=”y”;//start the loopwhile(another.equalsIgnoreCase(“y”)){//prompt the userSystem.out.print(“Enter a string to test whether or not it is a Palindrome; “);str= console.next();System.out.println();////the answerif(isPalindromeTest(str))System.out.println( str + “ is a palindrome”);elseSystem.out.println(str + “ not a palindrome”);System.out.print(“test another(y/n)? “);another= console.next();}}public static boolean isPalindromeTest(String str){return isPalindromeTest(str,0,str.length()-1);}public static boolean isPalindromeTest(String str,int low, int high){ if(high <= low)return true;else if (str.charAt(low)!= str.charAt(high))return false;elsereturn isPalindromeTest(str,low+1,high-1);}}

The output will display a message containing the string and proper character set.

Remove Specific Characters from a String

In the real world, this is a common function that a Java developer may be asked to perform for many different types of applications. It should be an easy task to complete without error. To remove specific characters from a string, the programmer will need to:

  1. Change the original string to a character array.
  2. Create a temporary boolean array (128 ASCII characters long) and set all the index values to “false.”
  3. Iterate through each character and declare each of the values in the temporary boolean array to “true.”
  4. Iterate through the original string variable copying each character where the value in the temporary boolean array is false.

How to Calculate the Total Number of Vowels in a String

Have your potential web programmer write a Java program that calculates the total number of vowels in a string variable. For example, the string “the bluebird flies south for the winter,” the output should equal 12.

Convert Lowercase to Uppercase in a String

Converting case is a common objective for programmers of all levels. Make sure your job candidate knows this one and can convert in both directions for any type of data.

Number Questions

Print the Fibonacci Series

Ask the programmer to write a snippet of code that prints out the Fibonacci Series. The result should be a series of numbers where after the initial two numbers, every occurring number is the sum of two preceding numbers. For example, 0,1,1,2,3,5,8,13,21… Advanced programmers will also know how to use a technique called memoization to improve the calculation created.

Armstrong Number

Ask your candidate to write a Java program that tests for an Armstrong number, which is a number that is equal to the sum of the cube of each digit.

For example: 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153. The variable in Java is coded into the example. Simple code to check for an Armstrong number would be:

class ArmstrongCheck{public static void main(String[] args) {int c=0,a,temp;int n=153;//is the number we are checkingtemp=n;while(n>0){a=n%10;n=n/10;c=c+(a*a*a);}if(temp==c)System.out.println(“Is an Armstrong number”);elseSystem.out.println(“Not an Armstrong number”);}}

Here, the output will not print any values but show a string saying “Is an Armstrong number, or Not an Armstrong number.”

Find the Factorial of any Given Number

Ask your job applicant to write a simple program that finds the factorial of any given number. You may also want to enhance this question by asking them to use iteration or recursive methods.

The Square Root of a Number

Have your potential Java developer create a script that finds the square root of a number. A simple example is:

package test;import java.util.Scanner;public class SquareRootTest{public static void main(String args[]) {Scanner scanner = new Scanner(System.in);System.out.println(“Enter a number to find the square root : “);double square = scanner.nextDouble();double squareRoot = Math.sqrt(square);System.out.printf(“The square root of the number: %f is : %f %n” , square, squareRoot);}}

Convert a Number to a Readable String

There are times when you want to convert a numeric value to a readable word or string. Example: 123 to one hundred and twenty-three. In this method, the programmer should know how to break down the object into units of tens, hundreds, thousands, or larger and then scan the digits, turning them into words declared in variables. The number to test is defined in the code.

Advanced Skills

Although many fresher Java developers can write code, you also want to test their problem-solving skills. Ask some of these more advanced Java programming interview questions to gain insight to their skill level.

Test for Iteration and Loop Skills

Ask your job candidate to write a Java program to iterate ArrayList using for-loop, while-loop, and advance for-loop. Although there are multiple ways this can be done, here is one code sample:

import java.util.*;public class arrayList {public static void main(String[] args) {ArrayList list = new ArrayList();list.add(“20”);list.add(“30”);list.add(“40”);System.out.println(list.size());System.out.println(“While Loop:”);Iterator itr = list.iterator();while(itr.hasNext()) {System.out.println(itr.next());}System.out.println(“Advanced For Loop:”);for(Object obj : list) {System.out.println(obj);}System.out.println(“For Loop:”);for(int i=0; i

Avoiding a Programming Deadlock

One of the more interesting Java interview coding questions is to ask the applicant to write a program where a resource is accessed by multiple threads but that no deadlock may occur. The trick to this one is acquiring resources in a specific order and then releasing them in reverse order. Quiz your interviewee on the techniques of using jConsole/VisualVM or fastthread.io to detect deadlock to then code a program that avoids it.

Remove Duplicates from an Array

Arrays are widely used in Java programming. A common function necessary to clean data is to remove any duplicates from an array. Test the programmer’s mettle by asking them not to use the Java Collection API in their process. You can supply the parameters that the array can be string, integer, or character, and the solution should solve for any type. The steps to resolve this one are:

  1. Copy all the array elements to LinkedHashSet.
  2. Empty the ArrayList to remove the elements and using the clear() method to start fresh.
  3. Copy the elements from LinkedHashSet to the new ArrayList.

How to Design a Vending Machine in Java

For advanced and higher-level coders, this question is invaluable to gauge the candidate’s expertise. First-timers will learn how to use some basics like encapsulation, polymorphism, or inheritance and some more subtle programming references like abstract class and interface for problem-solving. Java is an object-oriented language and asking a potential candidate to take a few hours to develop a fully functioning vending machine application will test their skills extensively. Some parameters for this assignment could be:

  • The program must accept coins of 1,5,10,25 cents (penny, nickel, dime, and a quarter).
  • The user must be able to select a product: Coke(25), Pepsi(35), Sprite(45).
  • Refund the deposit if the user cancels the request.
  • Process the sale and return any change.
  • Build in a reset button to start all over.

Calculate and Print All Permutations of a String

Have your Java programmer write a short script that returns all the possible permutations of a string (both text and numerical). For example, the letters DOG may be sorted six times (Dog, God, Ogd, Odg, Dgo, and Gdo). This test is a tricky one that requires recursion and loop techniques. A sample that would work is:

public class StringPermutations{ public static void main(String args[]) { permutation(“123”); }public static void permutation(String input){permutation(“”, input); }private static void permutation(String perm, String word){ if (word.isEmpty()) {System.err.println(perm + word);} else { for (int i = 0; i < word.length(); i++) {permutation(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1, word.length()));}}}}

The output for this example would be 123, 132, 213, 231, 312, 321.

Create a Bucket Sort

Bucket sort is becoming a popular Java programming interview question because it deals with creating a sophisticated sorting algorithm to sort through an array in linear time. To solve this one, the developer must use bucket sort to distribute the elements of an array into different “buckets” and then sort each of those using a different sorting algorithm by recursively applying the bucket sort algorithm. It’s an elegant solution to a complex question. The bucket sort problem can be solved in a few different ways. Using this question with your potential developer will help you learn about his or her creative approach to problem-solving and sorting techniques.

Bubble Sort

Although a bubble sort is inefficient and sparsely used in the real world, it is a good test of Java coding skills and technique. Typically, new programmers will learn this code in college. With a bubble sorting algorithm, the program keeps comparing the adjacent pair; if they aren’t in order, they swap position. This code repeats until it runs out elements. A sample piece of code that does this is:

import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Iterator;public class BubbleSort {public static int[] bubbleSort(int[] list) {for (int i = (list.length — 1); i >= 0; i — ) {for (int j = 1; j <= i; j++) {if (list[j — 1] > list[j]) {// swap elements at j-1 and jint temp = list[j — 1];list[j — 1] = list[j];list[j] = temp;}}}return list;}public static void main(String args[]) throws Exception{String list=””;int i=0,n=0;BubbleSort s= new BubbleSort();ArrayList arrlist=new ArrayList();System.out.println(“ “);System.out.println(“ “);System.out.println(“Please enter the list of elements,one element per line”);System.out.println(“ write ‘STOP’ when list is completed “);BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));while(!(list=bf.readLine()).equalsIgnoreCase(“stop”)){int intelement=Integer.parseInt(list);arrlist.add(intelement);}int elementlist[] = new int[arrlist.size()];Iterator iter = arrlist.iterator();for (int j=0;iter.hasNext();j++) {elementlist[j] = iter.next();}elementlist=bubbleSort(elementlist);System.out.println(“ “);System.out.println(“ “);System.out.println(“ “);System.out.println(“Values after Bubble Sort : “);for (int j=0;j

Iterate TreeMap in Java

Ask your candidate to write a small program that prints key/value pairs. A code sample from JavaHungry illustrating this method is below is:

import java.util.*;public class TreeMapIteratorExample {public static void main(String args[]) {// Declaring a TreeMap of String keys and String valuesTreeMap treemap = new TreeMap();// Add Key-Value pairs to TreeMaptreemap.put(“Key1”, “Pear”);treemap.put(“Key2”, “Apple”);treemap.put(“Key3”, “Orange”);treemap.put(“Key4”, “Papaya”);treemap.put(“Key5”, “Banana”);// Get Set of entriesSet set = treemap.entrySet();// Get iteratorIterator it = set.iterator();// Show TreeMap elementsSystem.out.println(“TreeMap contains: “);while(it.hasNext()) {Map.Entry pair = (Map.Entry)it.next();System.out.print(“Key is: “+pair.getKey() + “ and “);System.out.println(“Value is: “+pair.getValue());}}}

Other Java Programming Interview Questions

Along with the long list of trending Java programming interview questions listed above, there are some other things you will want to touch upon during the technical phase of the interview. Consider asking your Java candidate to describe in detail what the following list of programming terms mean:

  • Java runtime environment.
  • Data structure and algorithms.
  • Serialization process.
  • Ternary operator.
  • Polymorphism in Java.
  • Instantiated.
  • Subclasses.
  • HashMap in Java.
  • Java virtual machine jvm.
  • Binary.
  • Compiler.
  • Runtime
  • Instance.

The answers to these questions will give you a good sense of the caliber of coder they are. Some other more complicated tests given by high-level organizations before they hire a Java programmer are:

  • Open an Excel file and extract some data.
  • Checking to determine if a number is prime or not.
  • Demonstrate an explicit wait condition check.
  • Write a program to scroll up and scroll down.
  • Open links from a gmail.com account.
  • Write a code to switch between tabs.
  • Find the highest or second-highest number in an array.
  • Find the third element from the tail of a linked list.
  • Convert a linked list to a binary tree.
  • Sort a linked list.
  • Create an iterative QuickSort.

If your interviewee by default resorts to code reusability citing textbook code samples, you may want to keep interviewing. A good Java programmer will have exceptional problem-solving skills combined with a flair for creativity in coming up with original solutions created out of inspiration.

--

--

Responses (1)