Java Interview Questions

Practice for Java interviews by solving TestDome questions. Our interview questions are used by more than 7,000 companies and 450,000 individual test takers.

Jobseekers: Certify Your Knowledge

Take a Certification Test

Companies: Use Our Tests for Screening

Buy a Pack Of Candidates

Need to practice your Java programming skills for an upcoming job interview? Try solving these Java interview questions that test knowledge of Java programming concepts such as arrays, linked lists, inheritance, recursion, and other skills. We’ll provide feedback on your answers, and you can use a hint if you get stuck.

These Java interview questions are examples of real tasks used by employers to screen job candidates such as Java developers, back-end developers, mobile developers, and others that require knowledge of the Java programming language and its class library.

1. Cache Casting

Java Inheritance OOP Public

A company is designing the class hierarchy for various cache implementations:

public class Cache {}

public class DiskCache extends Cache {}

public class MemoryCache extends Cache {}

public class OptimizedDiskCache extends DiskCache {}

Select all the answers that will result in a runtime exception.

(Select all acceptable answers.)

Solve Question

2. Alert Service

Java Interfaces Inversion of Control Refactoring Public

Refactor the AlertService and MapAlertDAO classes:

  • Create a new package-private interface, named AlertDAO, that contains the same methods as MapAlertDAO.
  • MapAlertDAO should implement the AlertDAO interface.
  • AlertService should have a constructor that accepts AlertDAO.
  • The raiseAlert and getAlertTime methods should use the object passed through the constructor.
Solve Question

3. Merge Names

Java Arrays Public

Implement the uniqueNames method. When passed two arrays of names, it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.

For example, calling MergeNames.uniqueNames(new String[]{'Ava', 'Emma', 'Olivia'}, new String[]{'Olivia', 'Sophia', 'Emma'}) should return an array containing Ava, Emma, Olivia, and Sophia in any order.

Solve Question

4. Quadratic Equation

Java Arithmetic New Public

Implement the function findRoots to find the roots of the quadratic equation: ax2 + bx + c = 0. If the equation has only one solution, the function should return that solution as both elements of the Roots. The equation will always have at least one solution.

The roots of the quadratic equation can be found with the following formula: A quadratic equation.

For example, the roots of the equation 2x2 + 10x + 8 = 0 are -1 and -4.

Solve Question

5. Binary Search Tree

Java Algorithmic Thinking Recursion Tree Public

A three-node binary tree.Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.

Write a function that, efficiently with respect to time used, checks if a given binary search tree contains a given value.

For example, for the following tree:

  • n1 (Value: 1, Left: null, Right: null)
  • n2 (Value: 2, Left: n1, Right: n3)
  • n3 (Value: 3, Left: null, Right: null)

Call to contains(n2, 3) should return true since a tree with root at n2 contains number 3.

Solve Question

6. Song

Java Algorithmic Thinking HashSet Linked List Public

A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to null.

Implement a function isRepeatingPlaylist that, efficiently with respect to time used, returns true if a playlist is repeating or false if it is not.

For example, the following code prints "true" as both songs point to each other.

Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
Solve Question

7. User Input

Java Inheritance OOP Public

User interface contains two types of user input controls: TextInput, which accepts all characters and NumericInput, which accepts only digits.

Implement the class TextInput that contains:

  • Public method void add(char c) - adds the given character to the current value
  • Public method String getValue() - returns the current value

Implement the class NumericInput that:

  • Inherits from TextInput
  • Overrides the add method so that each non-numeric character is ignored

For example, the following code should output "10":

TextInput input = new NumericInput();
Solve Question

8. Account Test

Java Test Case Design Unit Testing Public

Using JUnit 4's Assert class, write tests for the Account class that cover the following cases:

  • The deposit and withdraw methods will not accept negative numbers.
  • Account cannot overstep its overdraft limit.
  • The deposit and withdraw methods will deposit or withdraw the correct amount, respectively.
  • The withdraw and deposit methods return the correct results.
public class Account {
    private double balance;
    private double overdraftLimit;
    public Account(double overdraftLimit) {
        this.balance = 0;
        this.overdraftLimit = overdraftLimit > 0 ? overdraftLimit : 0;
    public boolean deposit(double amount) {
        if(amount >= 0) {
            this.balance += amount;
            return true;
        return false;
    public boolean withdraw(double amount) {
        if(this.balance - amount >= -this.overdraftLimit && amount >= 0) {
            this.balance -= amount;
            return true;
        return false;
    public double getBalance() {
        return balance;
    public double getOverdraftLimit() {
        return overdraftLimit;

Each of the test case methods should be in the AccountTest class and have the Test annotation.

Solve Question

9. Two Sum

Java Algorithmic Thinking HashMap Public

Write a function that, when passed a list and a target sum, returns, efficiently with respect to time used, two distinct zero-based indices of any two of the numbers, whose sum is equal to the target sum. If there are no two numbers, the function should return null.

For example, findTwoSum(new int[] { 3, 1, 5, 7, 5, 9 }, 10) should return a single dimensional array with two elements and contain any of the following pairs of indices:

  • 0 and 3 (or 3 and 0) as 3 + 7 = 10
  • 1 and 5 (or 5 and 1) as 1 + 9 = 10
  • 2 and 4 (or 4 and 2) as 5 + 5 = 10
Solve Question

10. Decorator Stream

Java Stream Public

Implement methods in the DecoratorStream class:

  • write method should write the prefix into the underlying stream member only on the first write invocation. It should always write the bytes it receives to the underlying stream.
  • The prefix should be written in UTF-8 encoding.

For example, if the DecoratorStream is instantiated with "First line: " as the prefix parameter and write method is called with UTF-8 byte representation of "Hello, world!", it should write "First line: Hello, world!" into the underlying stream.

Solve Question

11. Folders

Java Serialization XML Public

Implement a function folderNames, which accepts a string containing an XML file that specifies folder structure and returns all folder names that start with startingLetter. The XML format is given in the example below.

For example, for the letter 'u' and an XML file:

<?xml version="1.0" encoding="UTF-8"?>
<folder name="c">
    <folder name="program files">
        <folder name="uninstall information" />
    <folder name="users" />

the function should return a collection with items "uninstall information" and "users" (in any order).

Solve Question

12. Sorted Search

Java Algorithmic Thinking Binary Search Public

Implement function countNumbers that accepts a sorted array of unique integers and, efficiently with respect to time used, counts the number of array elements that are less than the parameter lessThan.

For example, SortedSearch.countNumbers(new int[] { 1, 3, 5, 7 }, 4) should return 2 because there are two array elements less than 4.

Solve Question

13. Train Composition

Java Algorithmic Thinking Linked List Public

A TrainComposition is built by attaching and detaching wagons from the left and the right sides, efficiently with respect to time used.

For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13.

Implement a TrainComposition that models this problem.


Solve Question

14. Route Planner

Java 2D Array Algorithmic Thinking Graphs New Public

As a part of the route planner, the routeExists method is used as a quick filter if the destination is reachable, before using more computationally intensive procedures for finding the optimal route.

The roads on the map are rasterized and produce a matrix of boolean values - true if the road is present or false if it is not. The roads in the matrix are connected only if the road is immediately left, right, below or above it.

Finish the routeExists method so that it returns true if the destination is reachable or false if it is not. The fromRow and fromColumn parameters are the starting row and column in the mapMatrix. The toRow and toColumn are the destination row and column in the mapMatrix. The mapMatrix parameter is the above mentioned matrix produced from the map.

For example, for the given rasterized map, the code below should return true since the destination is reachable:

boolean[][] mapMatrix = {
    {true,  false, false},
    {true,  true,  false},
    {false, true,  true}
routeExists(0, 0, 2, 2, mapMatrix);
Solve Question

If you feel ready, take one of our timed public Java Interview Questions tests:

Java Online Test (Easy / Hard)

Java Algorithms Online Test (Easy / Hard)

Java Algorithms and SQL Online Test (Easy / Hard)

Java and Hibernate Online Test (Easy / Hard)

Java and Spring Boot Online Test (Easy / Hard)

Java and Spring Framework Online Test (Easy / Hard)

Java and SQL Online Test (Easy / Hard)

Java, Hibernate, and Spring Boot Online Test (Easy / Hard)

Java, Hibernate, and Spring Framework Online Test (Easy / Hard)


HTML/CSS, JavaScript, Java Algorithms, and SQL Online Test (Easy / Hard)

HTML/CSS, JavaScript, Java, and SQL Online Test (Easy / Hard)


Android and Java Online Test (Easy / Hard)

Not exactly what you are looking for? Go to our For Jobseekers section.
Dashboard Start Trial Sign In Home Tour Tests Questions Pricing For Jobseekers