Java Interview Questions

Want to become an expert in cracking Java interview questions?

Start with practicing the questions below. Whether a question involves multiple choice or live coding, we will give you hints as you go and tell you if your answers are correct or incorrect.

After that, take our timed public Java Interview Questions Test.

To use our service for testing candidates, buy a pack of candidates.


1. Alert Service

Java Refactoring Public New

Refactor the AlertService and MapAlertDAO classes:

  • Create a new package local 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.
Easy 
10min
Java SE 8
 


  •   MapAlertDAO implements AlertDAO interface: Wrong answer
  •   AlertService accepts AlertDAO in its constructor: Wrong answer
  •   The raiseAlert and getAlertTime methods use AlertDAO passed through constructor: Wrong answer


2. Merge Names

Java Arrays Public New

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.

Easy 
10min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at MergeNames.uniqueNames(MergeNames.java:4)
  •   Each array has distinct names: java.lang.UnsupportedOperationException at MergeNames.uniqueNames(MergeNames.java:4)
  •   Each array has duplicate names: java.lang.UnsupportedOperationException at MergeNames.uniqueNames(MergeNames.java:4)
  •   Arrays have some names in common: java.lang.UnsupportedOperationException at MergeNames.uniqueNames(MergeNames.java:4)


3. Palindrome

Java Strings Public

A palindrome is a word that reads the same backward or forward.

Write a function that checks if a given word is a palindrome. Character case should be ignored.

For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.

Easy  
10min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at Palindrome.isPalindrome(Palindrome.java:3)
  •   Lowercase words: java.lang.UnsupportedOperationException at Palindrome.isPalindrome(Palindrome.java:3)
  •   Various words: java.lang.UnsupportedOperationException at Palindrome.isPalindrome(Palindrome.java:3)


4. Account Test

Java Test case design Public New

Using JUnit 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.

Easy 
15min
Java SE 8
 


  •   The deposit and withdraw methods will not accept negative numbers: Wrong answer
  •   Account cannot overstep its overdraft limit: Wrong answer
  •   The deposit and withdraw methods will deposit or withdraw the correct amount, respectively: Wrong answer
  •   The withdraw and deposit methods return the correct results: Wrong answer


5. Binary Search Tree

Java Algorithmic thinking Data structures 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.

Easy  
15min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at BinarySearchTree.contains(BinarySearchTree.java:14)
  •   Correctness: java.lang.UnsupportedOperationException at BinarySearchTree.contains(BinarySearchTree.java:14)
  •   Performance test on a large tree: java.lang.UnsupportedOperationException at BinarySearchTree.contains(BinarySearchTree.java:14)


6. Playlist

Java Algorithmic thinking Searching Public New

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");
    
first.setNextSong(second);
second.setNextSong(first);
    
System.out.println(first.isRepeatingPlaylist());
Easy  
15min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at Playlist$Song.isRepeatingPlaylist(Playlist.java:15)
  •   Song will repeat: java.lang.UnsupportedOperationException at Playlist$Song.isRepeatingPlaylist(Playlist.java:15)
  •   Song will not repeat: java.lang.UnsupportedOperationException at Playlist$Song.isRepeatingPlaylist(Playlist.java:15)
  •   Performance test on a large playlist: java.lang.UnsupportedOperationException at Playlist$Song.isRepeatingPlaylist(Playlist.java:15)


7. User Input

Java 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();
input.add('1');
input.add('a');
input.add('0');
System.out.println(input.getValue());
Easy  
15min
Java SE 8
 


  •   Example case: java.lang.ClassCastException
  •   Adding various characters to TextInput: java.lang.NoSuchMethodException
  •   Adding numeric characters to NumericInput: java.lang.ClassCastException
  •   Adding various characters to NumericInput: java.lang.ClassCastException


8. Two Sum

Java Algorithmic thinking Searching 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
Easy  
30min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at TwoSum.findTwoSum(TwoSum.java:3)
  •   Distinct numbers with and without solutions: java.lang.UnsupportedOperationException at TwoSum.findTwoSum(TwoSum.java:3)
  •   Duplicate numbers with and without solutions: java.lang.UnsupportedOperationException at TwoSum.findTwoSum(TwoSum.java:3)
  •   Performance test with a large list of numbers: java.lang.UnsupportedOperationException at TwoSum.findTwoSum(TwoSum.java:3)


9. Decorator Stream

Java Stream Public New

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.

Hard 
15min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at DecoratorStream.write(DecoratorStream.java:33)
  •   DecoratorStream writes to the stream: java.lang.UnsupportedOperationException at DecoratorStream.write(DecoratorStream.java:33)
  •   DecoratorStream writes the prefix using UTF-8 encoding: java.lang.UnsupportedOperationException at DecoratorStream.write(DecoratorStream.java:33)


10. Folders

Java Serialization 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>
    <folder name="users" />
</folder>

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

Hard  
20min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at Folders.folderNames(Folders.java:5)
  •   All folder names start with starting letter: java.lang.UnsupportedOperationException at Folders.folderNames(Folders.java:5)
  •   Complicated folder structure: java.lang.UnsupportedOperationException at Folders.folderNames(Folders.java:5)


11. Sorted Search

Java Algorithmic thinking Searching 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.

Hard  
20min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at SortedSearch.countNumbers(SortedSearch.java:3)
  •   Various small arrays: java.lang.UnsupportedOperationException at SortedSearch.countNumbers(SortedSearch.java:3)
  •   Performance test when sortedArray contains lessThan: java.lang.UnsupportedOperationException at SortedSearch.countNumbers(SortedSearch.java:3)
  •   Performance test when sortedArray doesn't contain lessThan: java.lang.UnsupportedOperationException at SortedSearch.countNumbers(SortedSearch.java:3)


12. Train Composition

Java Algorithmic thinking Data structures 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.

train

Hard  
20min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at TrainComposition.attachWagonFromLeft(TrainComposition.java:3)
  •   Several wagons: java.lang.UnsupportedOperationException at TrainComposition.attachWagonFromRight(TrainComposition.java:7)
  •   Performance test with a large number of wagons: java.lang.UnsupportedOperationException at TrainComposition.attachWagonFromRight(TrainComposition.java:7)


13. Path

Java Data structures Strings Public

Write a function that provides change directory (cd) function for an abstract file system.

Notes:

  • Root path is '/'.
  • Path separator is '/'.
  • Parent directory is addressable as "..".
  • Directory names consist only of English alphabet letters (A-Z and a-z).
  • The function should support both relative and absolute paths.
  • The function will not be passed any invalid paths.
  • Do not use built-in path-related functions.

For example:

Path path = new Path("/a/b/c/d");
path.cd('../x');
System.out.println(path.getPath());

should display '/a/b/c/x'.

Hard  
30min
Java SE 8
 


  •   Example case: java.lang.UnsupportedOperationException at Path.cd(Path.java:13)
  •   Selecting child directories: java.lang.UnsupportedOperationException at Path.cd(Path.java:13)
  •   Selecting parent directories: java.lang.UnsupportedOperationException at Path.cd(Path.java:13)
  •   Selecting complex paths: java.lang.UnsupportedOperationException at Path.cd(Path.java:13)


If you feel ready, take one of our timed public Java Interview Questions tests:
  • Android and Java 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)
  • Java Online Test (Easy / Hard)
  • Java Algorithms Online Test (Easy / Hard)
  • Java Algorithms and SQL Online Test (Easy / Hard)
  • Java and Spring Framework Online Test (Easy / Hard)
  • Java and SQL Online Test (Easy / Hard)
Not exactly what you are looking for? Go to our For Jobseekers section.