As a professional freelance programmer I have sat through (and conducted) my fair share of Java technical tests. They are usually the first step when applying for a role so you have make sure that you are familiar with what answers are expected. Usually this means digging out some books and doing some revision. What I have found is that the topics covered are almost always the same. I've also found that it's really easy to forget some of the areas that can come up.
Javonical is here help. It is the canonical collection of Java technical questions to save you hunting around lots of sources before that important first interview.
The approach I have settled on is to group the questions under some broad headings and to express the questions as if they were being asked. I will annotate each question to make it clear what is being asked and then provide what should go into your answer. I will not be trying to give the answers verbatim because that needs to be in your words.
I have also included some code examples because often that is the best way to understand things.
Enough explanation lets begin.
"Hi, thanks for coming today. Lets start with a few technical questions..."
"What are the differences between instances, classes, abstract classes and interfaces?"
"What visibility modifiers can be added to a field and what is the order of their visibility?"
Most visible first: public, protected, package private, private.
"What does the transient keyword do?"
Stops that field from being serialized.
"What does the static keyword mean, and where can it be used?"
Variables, method, classes and blocks.
"Describe how memory leaks can occur in Java?"
"What class does Java provide that can be used to avoid memory leaks?"
WeakReference
"What is an enum and how do you use one?"
"Name the 4 base collection interfaces and some of the implementations."
Map, Set, List, Queue...
ArrayList, HashMap, HashSet, CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentHashMap, Vector, Hashtable, LinkedList, Stack, TreeMap, TreeSet, LinkedHashMap, LinkedHashSet, EnumMap...
"Compare and contrast the LinkedList and ArrayList?"
"What do you understand Big O notation to be?"
wiki: A way of denoting how well an algorithm performs. A measure of complexity or performance.
"How is a HashMap implemented?"
Buckets, LinkedList, hashcode, equals
In JEP-180 HashMap has been improved. From the original proposal:
The principal idea is that once the number of items in a hash bucket grows beyond a certain threshold, that bucket will switch from using a linked list of entries to a balanced tree. In the case of high hash collisions, this will improve worst-case performance from O(n) to O(log n)
More information from Tomasz Nurkiewicz HashMap improvements
"What is the different between a checked and an unchecked exception?"
"Explain what the 'finally' block does"
(This is the standard Java interview question so you need to be able to get it right. You need to be able to answer this without any waffle)
"What is the contract between hashcode and equals?"
"Explain how hashcode and equals are used when doing a "put" into a hash map?"
"What property must the class have to be used as the key in a Map?"
It must be immutable otherwise the wrong bucket will be searched during a lookup in the Map.
(Lets not mess about, multithreading is the single most common subject that will come up. Never mind that in 90% of cases the role itself wont include any multithreading at all)
"How do you start a new thread?"
"What does the synchronized keyword do?"
"What is the difference between a Runnable and a Callable?"
"Could you tell me what a Future is?"
"How do you make a class thread-safe?"
"What are the benefits of a class being immutable?"
An immutable class means that it cannot change.
"Explain what steps you can take to make a class immutable"
You need to ensure that it cannot be changed either by enforcement (Make the fields final, values set in the constructor and if they are not primitive then the object being referred to cannot change either) or by convention (Simply agree that objects will never be changed).
"What are the options for handling InterruptedException?"
- Rethrow it. That may not be possible if it's in a Runnable though, for instance.
- Handle it with some specific logic that makes sense.
- Interrupt the thread and move on.
Thread.currentThread().interrupt();
Do not just log and ignore the exception.
"Explain what a monitor is and how they are used?"
"What is the different between StringBuffer and StringBuilder?"
This here because the difference is that StringBuffer is synchronized and StringBuilder is not.
"Explain what a CountDownLatch is and how it differs from a CyclicBarrier"
"What does the 'volatile' keyword do when found on a field and how would you use it?"
Interesting article
"Without using the classes in the java.util.concurrency package implement a blocking queue"
First step is to look at the implementation I've put together here. Look at the Producer and Consumer and see how they use the blocking queue). The critical things to be able to able to answer are:
- Why are both methods synchronized?
- Why is the wait() surrounded by a while loop?
- Why is notifyAll() used rather than notify()?
A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:
synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}
"How would you go about determining what is causing a deadlock?"
"What do you understand by the term 'happens before'?"
Java Memory Model, JSR-133
(Another interview classic and it helps to be able to draw a picture describing Eden Space, 2x Survivor Spaces, Old Gen, Perm Gen)
"How does an object become eligible for garbage collection?"
"There are several different garbage collection implementations, describe the one that you are most familiar with."
There are basically 3; Serial (for single core and no pause time requirements), Parallel (peak performance and no pause time requirements) and ConcurrentMarkSweep (overall throughput and GC pauses of under a second).
"Describe how the memory organised within the JVM and how objects are moved around inside it"
"How can you ensure that an object is garbage collected immediately?"
Trick question, you can't. System.gc() will suggest to the JVM that it should run the garbage collection but it is under no obligation to actually do it.
"Could you tell me what is type erasure is?"
"Would a class compile if it had 2 methods on which both had the same return value and both took a single parameter, one being List<String>
and the other being List<Date>
."
No. Type erasure would removed the type of the List in both methods leaving both methods with the same signature.
"What is the difference between 'super' and 'extends'?"
PECS. Producer Extends, Consumer Super.
The first says that it's "some type which is a subclass of E"; the second says that it's "some type which is an ancestor of E". (In both cases E itself is okay.)
StackOverflow Question
"Write a method that implements a factorial (The product of all the positive integers from 1 to a given number. Factorial 0 is 1."
public static int factorial(int f) {
return ((f == 0) ? 1 : f * factorial(f - 1));
}
"Write some methods to traverse a tree or graph" This comes up quite a bit. (MH - Several times for me now). When it does its a killer if you have not got the principles nailed in advance. Your answer will depend on what they are asking you to operate on to some extent but the principles are easy to learn. Good starting places include:
(You just know that you are going to be asked to implement a Singleton eventually so best you know how to do it. It's worth being able to describe a few more as well.)
"Could you explain what a design pattern is?"
"What are some of the most well known patterns?"
"When is it a good time to use a pattern discuss?"
This is designed to get you to talk about patterns in design. Should you always use patterns? They add complexity! Sometimes overkill etc.
"How do you implement a Singleton?"
You talk to Mr Josh Bloch:
public enum Singleton {
INSTANCE;
}
"How would you lazy load the instance in a singleton?"
private static class LazySomethingHolder {
public static Something something = new Something();
}
public static Something getInstance() {
return LazySomethingHolder.something;
}
"How do you test your code?"
"Could you name some mocking frameworks?"
EasyMock, JMock, Mockito, JMockit
"Describe the benefits of using mocking framework?"
"Explain why dependency injection is important when mocking"
If I had to pick up just one book to revise from it would be Java Concurrency in Practice by Brian Goetz et al. If you can nail the multithreading part of the test then it goes a hell of a long way.
Another book you really should have read is Effective Java by Josh Bloch. Reading that book totally changes the way in which you code Java.
Top-15 Investment Bank Threading Questions
- Matt Biggin (matthew.biggin@gmail.com)
- Martin Harris