Java Interview: Coding Questions and Answers

November 21st, 2011 Leave a comment
Like the article?
Java Interview

Interviewing for a job can be stressful, but if there is one thing that can add more complexity to the interview process, it would be the technical interview. Nothing strikes fear in the heart of developers faster than the thought of sweating hands and an interview’s stare as you struggle through a coding problem on a whiteboard. This is the stuff of nightmares.

It is natural for you to fear this process since many programmers, new and veteran alike, have doubts about their coding abilities. The best thing you can do is prepare yourself for what is to come. There are very few Java programming jobs that will hire a programmer without a basic hands-on interview so they can get an idea of the interviewee’s skills. This article will discuss three common Java interview questions with coding examples that interviewers may present you with. There are many other guides online that can help you with the questions that interviewers may ask; this article is going to focus only on coding problems.

Question 1: Explain the difference between sleep() and wait(). Give an example of how they can be used.

This is a good starter question for interviewers since it helps to define the scope of the interviewee’s experience. If you have never worked with threads, you have probably never worried about the sleep() and wait() methods. Here is the difference:

The wait() method tells the thread of release the lock that it has on an object for a specified amount of time given as an argument. The common usage is to use wait() when you have another thread that needs to run. It can be called like: wait(), wait(long timeout), or wait(long timeout, int nanos). The timeout argument needs to be given in milliseconds and the nanos argument in nanoseconds. wait() cannot be called by other threads and must be called on the thread that owns the lock on the object in question.

wait() will put the thread on hold and it will be disabled for scheduling until either the wait timeout has run out or, in the case of indefinite timeout period, you must call the notify() or notifyAll() methods for the object to make the thread re-available for scheduling. Your other option would be to have another thread interrupt the thread on hold in which case an InterruptedException will be thrown.

Example of usage for wait():

synchronized(myObject) {
	while (myObject.isEmpty()) {
	return myObject.remove(0);

wait() must be called in a synchronized context to not violate the “wait() must only be called from the owner” rule. It is a good rule of thumb to run isEmpty() so you know if you should wait or not. In this case since there is no specified timeout on wait() it will wait indefinitely until notify() is called.

sleep() on the other hand is a different animal that works a little bit different from wait() but since the two can get confused, let’s explore.

sleep() causes the current thread to become disabled and “sleep” for a specified amount of time. It is often used when you have other threads running that need the resources that this thread is using and you want to free them up. sleep() is often used to control the pacing of your program or when you are waiting for other threads to finish their tasks.

There are two overloads for sleep(). Much like wait(), you can call sleep() with the specified sleep time in milliseconds such as sleep(5000), or you can call it with the sleep time to the nanosecond. There is no need to “wake” a sleeping thread since it will re-awaken when the sleep duration is over, however a sleeping thread can be interrupted by other actions.

Example of usage for sleep():

String myMessages[] = {
	"Mary had a little lamb",
	"His fleece was white as snow",
	"Everywhere that Mary went",
	"The lamb was sure to go"

for (int i = 0; i < myMessages.length; i++) {
	// pause for five seconds between each line
	// print one of the lines

As you can see it is easy to confuse the two but they are very different methods in their behavior and methods of usage. Be sure to highlight the differences if given this question to show that you have a good grasp of the implications.

ADDENDUM: Based on the comment below from Musk,

the most important difference between sleep and wait is that wait will release locks it holds and enable other threads to pick them up because of this it has to be executed in a synchronized block. Sleep on the other hand doesn’t release locks it holds and will therefor block threads waiting on the lock. Using sleep in a multi-threaded enviorment can be a garant to creating deadlocks.

Question 2: Explain Synchronization and show an example of how it is used.

Synchronization is the process of controlling access to a shared resource when using multiple threads in your program. The problem in multi-threaded applications is that threads often need to share access to a common resource or piece of data but they are only allowed to access these resources one at a time. To prevent data corruption and to keep processes from stepping on each other’s toes, synchronization can be used to keep everything orderly.

Because synchronization is an important part of large application development, this is a well-used interview coding question. If you want to show your interviewer that you are a prepared and knowledgeable developer, be ready for questions about synchronization.

To use synchronization we simply put the synchronized keyword in front of the method we wish to be synchronized and it will no longer be accessible by more than one thread at a time. Locking will be available to help this process.

Here is an example:

public class Counting {
	public static synchronized count() {
		return this.count;

	public static synchronized myCounter(int count) {
		this.count = count;

Simple right? Yes, but highly effective. Since both methods are static and synchronized they will lock on to the same this.count reference and be incapable of returning an incorrect count result if another thread tries to access the data.

Question 3: Give me an example of how you would use the final keyword.

The final keyword is a good example of something you would see in an interview since it is obscure enough that newer developers may not understand its use or be able to explain it, let alone come up with an example.

The final keyword can be used with variables, fields, methods and classes. It is a negative action keyword since its application prevents these constructs from being set, overridden, hidden or extended. You would can the final keyword to ensure the correctness of code so that variables cannot be reassigned or, in the case of anonymous local classes, where variables and parameters must be declared final. One of the most used instances of final is to flag constants when used with static.

Ok, so you know what it is. How would you use it?

To create a variable that has the behavior of a constant that once set cannot be changed.

final int myInt = 1; // creates a constant integer 
myInt = 5; // not allowed

To create a field as final you must only assign it once. It must be initialized by the constructor of its class or be assigned to directly where it is defined.

public class MyFinalClass {
	private final int myInt = 1;

public class MyFinalClass {
	private final int myInt;

	public MyFinalClass() {
		myInt = 1;

With the final keyword you can program with a certain amount of assurance that certain values have not changed and that the code is correct. This gives your code a new robustness since you know that objects would be fully initialized and that all fields had a value. Why final has fallen by the wayside is beyond me since it is a great tool for writing better code.

ADDENDUM: Another thoughtful addition by Musk:

final does not produce constants it produces constant references. In the given example the int is a constant because it is a primitive. If used with a immutable object it will also produce a constant but if used with a type that allows mutation the reference can’t be changed the object this reference points to may very well be changed although it is final.

Remember that this guide is not comprehensive by any means, but should be used to give you an idea of what you will face in your technical interview. Your best defense against fear is preparation, so get out there and study!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!