Java Online Test
For jobseekers
Practice your skills and earn a certificate of achievement when you score in the top 25%.
Take a Practice TestFor companies
Test candidates with real-world problems and interview the best ones.
Sign Up to Offer this TestAbout the test
The Java online test assesses knowledge of programming in the Java language and commonly used parts of the Java Class Library. This test requires solving live coding problems in Java.
The assessment includes work-sample tasks such as:
- Working with classes, objects, and interfaces to write reusable code.
- Using proper algorithms and data structures to optimize application performance.
- Taking advantage of the Java Class Library.
A good Java developer needs a solid understanding of the Java programming language as well as the Java Class Library and its functionality to write robust and maintainable code.
Sample public questions
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 public constructor that accepts AlertDAO.
- The raiseAlert and getAlertTime methods should use the object passed through the constructor.
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 anarray containing Ava, Emma, Olivia, and Sophia in any order.
Your company is analyzing malware that targets numerical record files stored in an array.
The malware adjusts values at both the edges of the array using a window of size 's' as shown in the video below:
Implement the simulate method so that the malware behavior is replicated for further study.
A gaming company is working on a platformer game. They need a method that will compute the character's final speed, given a map and a starting speed.
The terrain on which the game character moves forward is made from various pieces of land placed together. Implement the method calculateFinalSpeed which takes the initial speed of the character, and an array of degrees of inclination that represent the uneven terrain.
The speed of the character will increase or decrease proportionally to the incline of the land, as shown in the image below:
[画像:Image showing the increase and decrease of character speed.]
The magnitude of the angle of inclination will always be < 90°. The speed change occurs only once for each piece of land. The method should immediately return 0 as the final speed if an incline reduces the speed to 0 or below 0, which makes the character lose 1 life.
For example, the below code:
System.out.println(calculateFinalSpeed(60.0, new int[] { 0, 30, 0, -45, 0 }));
should print:
75
A turn-based strategy game has a grid with water and land. The grid contains a true value where it's water and false where it's land.
The player controls a boat unit with a particular movement pattern. It can only move to fixed destinations from its current position as shown in the video below:
The boat can only move in a direct path through water to the possible destinations, so a destination will become unreachable if there is land in the way.
Implement the canTravelTo function, that checks whether a destination is reachable by the boat. It should return true for destinations that are reachable according to the pattern above, and false for unreachable or out of bounds destinations which are outside the grid.
For example, consider the following code:
boolean[][] gameMatrix = {
{false, true, true, false, false, false},
{true, true, true, false, false, false},
{true, true, true, true, true, true},
{false, true, true, false, true, true},
{false, true, true, true, false, true},
{false, false, false, false, false, false},
};
System.out.println(canTravelTo(gameMatrix, 3, 2, 2, 2)); // true, Valid move
System.out.println(canTravelTo(gameMatrix, 3, 2, 3, 4)); // false, Can't travel through land
System.out.println(canTravelTo(gameMatrix, 3, 2, 6, 2)); // false, Out of bounds
The following image shows valid and invalid destinations when the boat is in the position (3, 2):
A megastore offers three types of discounts, which are represented as DiscountType enum.
Implement the getDiscountedPrice method which should take the total weight of the shopping cart, the total price, and the discount type. It should return the final discounted price based on the discount schemes as shown in the promotional video below:
(Open full-size video in a new tab)
For example, the following code:
System.out.println(getDiscountedPrice(12, 100, DiscountType.Weight));
should print:
82.0
Implement the function findRoots to find the roots of the quadratic equation: ax2 + bx + c = 0. The function should return a Roots object containing roots in any order. 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, findRoots(2, 10, 8) should return a Roots object where either x1 = -1, x2 = -4 or x1 = -4, x2 = -1 as the roots of the equation 2x2 + 10x + 8 = 0 are -1 and -4.
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);
Implement the IceCreamMachine's scoops method so that it returns all combinations of one ingredient and one topping. If there are no ingredients or toppings, the method should return an empty list.
For example,
IceCreamMachine machine = new IceCreamMachine(
new String[]{"vanilla", "chocolate"},
new String[]{"chocolate sauce"}
);
List<IceCream> scoops = machine.scoops();
for (IceCream iceCream : scoops) {
System.out.println(iceCream.ingredient + ", " + iceCream.topping);
}
should print
vanilla, chocolate sauce
chocolate, chocolate sauce
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 isInRepeatingPlaylist 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.isInRepeatingPlaylist());
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.
Write a function that, when passed a list and a target sum, returns, efficiently with respect to time used, two distinctzero-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
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]
[画像: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.
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.
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());
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).
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.
You are working on a calculator application where users can input a mathematical expression such as: (3 + 5) * (2 - 4).
To correctly evaluate this expression, the application needs to validate the expression and ensure that the parentheses are balanced. The balanced parentheses are crucial for determining the order of operations and evaluating the expression correctly.
You have used an AI assistant to generate the following static method to check if the parentheses in an expression are balanced:
public static boolean isBalanced(String parentheses) {
Stack<Character> stack = new Stack<>();
Set<Character> opening = new HashSet<>(Arrays.asList('(', '[', '{'));
Set<Character> closing = new HashSet<>(Arrays.asList(')', ']', '}'));
Map<Character, Character> pairs = new HashMap<>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
for (char c : parentheses.toCharArray()) {
if (opening.contains(c)) {
stack.push(c);
} else if (closing.contains(c)) {
if (stack.isEmpty() || stack.peek() != pairs.get(c)) {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
What is correct for the given method?
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.
For jobseekers: get certified
Earn a free certificate by achieving top 25% on the Java test with public questions.
Take a Certification TestSample silver certificate
Sunshine Caprio
Java and SQL TestDomeCertificate TestDome logo icon
For companies: premium questions
Buy TestDome to access premium questions that can't be practiced.
Get money back if you find any premium question answered online.
Ready to interview?
Use these and other questions from our library with our
Code Interview Platform.
78 more premium Java questions
Document Store , Driver Exam , Chain Link , Document Counter , Hobbies , Product , Snapshot , Snow Storm , Utilities , Weighted Average , Shining Star , Crop Ratio , Integer Utilities , Fire Dragon , Log Parser , String Occurrence , Worker , Segment , Shelf Test , Read Write Execute , Read First Line , Max Sum , Unique Numbers , Friend , Stories , Moving Total , Internal Nodes , Veterinarian , Wheel Defects , Paper Strip , Flight Connections , Language Teacher , Vectors , Racer , Mock Library , Patient Class , Reward Points , Tax Calculator , Test Results , Numbers To Text , Ceramic Store , Stack to List , Config Element , Tiles , New Folder , Paragraph , Animal Hierarchy , Procedural Generator , Action Stack , Node , Calories Burned , Kilometer Converter , Construction Game , Date Transform , Platformer , Company Stock , Chemical Machine , Adventure Game , Seasonal Tourism , Candies , Shipping , Speed Monitor , Parking Allocation , Planet Search , Special Actions , Ecological Experiment , Automated Forklift , Digital Flasks , Popular Book , Car Rental , Username , Flimsy Bridge , Unique Product , Book Sale , Circuit Simulator , Airport Networks , Jobs Time , Christmas Lights .
Skills and topics tested
- Java
- Bug Fixing
- Language
- Exceptions
- Linked List
- OOP
- Refactoring
- HashMap
- Iteration
- Lists
- Accessibility Levels
- ArrayList
- Class Modifiers
- Arithmetic
- TDD
- Integer Division
- Performance Tuning
- Higher Order Function
- Interfaces
- Serialization
- XML
- Stream
- Strings
- Memory Management
- Test Case Design
- Unit Testing
- Algorithmic Thinking
- Graphs
- Dynamic Programming
- HashSet
- Arrays
- Tree
- Queue
- StringBuilder
- Inheritance
- Multithreading
- Synchronization
- Dynamic Proxy Classes
- Abstract Class
- Classes
- Objects
- Stream API
- Complexity
- Stack
- Generics
- Regex
- Random
- Recursion
- Method Overriding
- Video
- Data Structures
- AI Code Review
- Conditional Statements
- Loops
- Conditions
- 2D Array
- Dictionary
- Sorting
For job roles
- Back-End Developer
- Java Developer
- Web Developer
Sample candidate report
Need it fast? AI-crafted tests for your job role
TestDome generates custom tests tailored to the specific skills you need for your job role.
Sign up now to try it out and see how AI can streamline your hiring process!
What others say
Simple, straight-forward technical testing
TestDome is simple, provides a reasonable (though not extensive) battery of tests to choose from, and doesn't take the candidate an inordinate amount of time. It also simulates working pressure with the time limits.
Jan Opperman, Grindrod Bank
Product reviews
Used by
Solve all your skill testing needs
150+ Pre-made tests
130+ skills
Multi-skills Test
How TestDome works
Choose a pre-made test
or create a custom test
Invite candidates via
email, URL, or your ATS
Candidates take
a test remotely
Sort candidates and
get individual reports