0% found this document useful (0 votes)
682 views

Top 18 Java Design Pattern Interview Questions Answers For Experienced

This document discusses design pattern interview questions for Java programmers. It provides 18 common design pattern questions asked during Java interviews and summarizes the key design patterns like Strategy, Observer, Decorator, Singleton, and Factory. It emphasizes that experienced Java developers should be familiar with design patterns and able to apply them to real-world problems. The purpose is to evaluate a candidate's understanding of essential design patterns and how to use them properly in Java applications.

Uploaded by

Denny Arshan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
682 views

Top 18 Java Design Pattern Interview Questions Answers For Experienced

This document discusses design pattern interview questions for Java programmers. It provides 18 common design pattern questions asked during Java interviews and summarizes the key design patterns like Strategy, Observer, Decorator, Singleton, and Factory. It emphasizes that experienced Java developers should be familiar with design patterns and able to apply them to real-world problems. The purpose is to evaluate a candidate's understanding of essential design patterns and how to use them properly in Java applications.

Uploaded by

Denny Arshan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Top 18 Java Design Pattern Interview Questions Answers for

Experienced
Design pattern interview question in Java
design pattern interview question are integral part of any good list of core Java interview questions. Java
is a popular Object oriented programming language and have lots of design pattern and design principles,
contributed by many developers and open source framework. As a Java programmer its expected from
you to know OOPS concept like Abstraction, Encapsulation and polymorphism, What is design pattern in
Java, Some popular Java design pattern and most importantly when to use those design pattern in Java
application. purpose of asking design pattern interview question in Java is to check whether Java
programmer are familiar to those essential design patterns or not. Design patterns in Java interviews are
as important as multi-threading, collection and programming questions. If you are senior or experienced
Java programmer than expect more complex and tough design pattern in Java interview e.g. Chain of
responsibility design pattern and solving real timesoftware design questions.

Top Java design pattern questions and answers

Here is my list of top 10 design pattern interview question in Java. I have also provided answer of
those Java design pattern question as link. no matter which level of Java interview are you going e.g.
programmer,software engineer, senior software engineer in Java, you can expect few question from Java
design pattern.

1. When to use Strategy Design Pattern in Java?


Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms,
filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses
Strategy implementation classes for applying business rules. This pattern follow open closed design
principle and quite useful in Java. One example of Strategy pattern from JDK itself is
a Collections.sort() method and Comparator interface, which is a strategy interface and defines
strategy for comparing objects. Because of this pattern, we don't need to modify sort() method (closed
for modification) to compare any object, at same time we can implement Comparator interface to define
new comparing strategy (open for extension).

2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview question. Observer pattern is based upon
notification, there are two kinds of object Subject and Observer. Whenever there is change on subject's
state observer will receive notification. See What is Observer design pattern in Java with real life
example for more details.

3. Difference between Strategy and State design Pattern in Java?


This is an interesting Java design pattern interview questions as both Strategy and State pattern has
same structure. If you look at UML class diagram for both pattern they look exactly same, but there intent
is totally different. State design pattern is used to define and mange state of object, while Strategy pattern
is used to define a set of interchangeable algorithm and let's client to choose one of them. So Strategy
pattern is a client driven pattern while Object can manage there state itself.

4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular java design pattern question which is common because of its heavy
usage injava.io package. BufferedReader and BufferedWriter are good example of decorator
pattern in Java. SeeHow to use Decorator pattern in Java fore more details.

5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with Composite
pattern but also, whether candidate has real life experience or not. Composite pattern is also a core Java
design pattern, which allows you to treat both whole and part object to treat in similar way. Client code,
which deals with Composite or individual object doesn't differentiate on them, it is possible because
Composite class also implement same interface as there individual part. One of the good example of
Composite pattern from JDK is JPanel class, which is both Component and Container.
When paint() method is called on JPanel, it internally called paint() method of individual
components and let them draw themselves. On second part of this design pattern interview question, be
truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by
your own. By the way always remember, giving an example from your project creates better impression.

6. What is Singleton pattern in Java?


Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole
application. java.lang.Runtime is good example of Singleton pattern in Java. There are lot's of follow up
questions on Singleton pattern see 10 Java singleton interview question answers for those followups

7. Can you write thread-safe Singleton in Java?


There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double
checked locking, by using static Singleton instance initialized during class loading. By the way using
Java enum to create thread-safe singleton is most simple way. See Why Enum singleton is better in
Java for more details.

8. When to use Template method design Pattern in Java?Template pattern is another popular core
Java design pattern interview question. I have seen it appear many times in real life project itself.
Template pattern outlines an algorithm in form of template method and let subclass implement individual
steps. Key point to mention, while answering this question is that template method should be final, so that
subclass can not override and change steps of algorithm, but same time individual step should be
abstract, so that child classes can implement them.

9. What is Factory pattern in Java? What is advantage of using static factory method to create
object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews.Factory
pattern used to create object by providing static factory methods. There are many advantage of providing
factory methods e.g. caching immutable objects, easy to introduce new objects etc. See What is Factory
pattern in Java and benefits for more details.

10. Difference between Decorator and Proxy pattern in Java?Another tricky Java design pattern
question and trick here is that both Decorator and Proxy implements interface of the object they decorate
or encapsulate. As I said, many Java design pattern can have similar or exactly same structure but they
differ in there intent. Decorator pattern is used to implement functionality on already created object, while
Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy
design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy
actually creates objects.

11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor injection to
provide mandatory dependency of an object, without which it can not work. This question is related
to Dependency Injection design patternand mostly asked in context of Spring framework, which is now
become an standard for developing Java application. Since Spring provides IOC container, it also gives
you way to specify dependencies either by using setter methods or constructors. You can also take a look
my previous post on same topic.

12. What is difference between Factory and Abstract factory in Java


see here to answer this Java design pattern interview question.
13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern
can also be used to encapsulate third party code, so that your application only depends upon Adapter,
which can adapt itself when third party code changes or you moved to a different third party library. By the
way this Java design pattern question can also be asked by providing actual scenario.

14. Can you write code to implement producer consumer design pattern in Java?
Producer consumer design pattern is a concurrency design pattern in Java which can be implemented
using multiple way. if you are working in Java 5 then its better to use Concurrency util to implement
producer consumer pattern instead of plain old wait and notify in Java. Here is a good example of
implementing producer consumer problem using BlockingQueue in Java.

15. What is Open closed design principle in Java?


Open closed design principle is one of the SOLID principle defined by Robert C. Martin, popularly known
as Uncle Bob. This principle advices that a code should be open for extension but close for modification.
At first this may look conflicting but once you explore power of polymorphism, you will start finding
patterns which can provide stability and flexibility of this principle. One of the key example of this is State
and Strategy design pattern, where Context class is closed for modification and new functionality is
provided by writing new code by implementing new state of strategy. See this article to know more about
Open closed principle.

16. What is Builder design pattern in Java? When do you use Builder pattern ?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews
because of its specific use when you need to build an object which requires multiple properties some
optional and some mandatory. See When to use Builder pattern in Java for more details

17. Can you give an example of SOLID design principles in Java?


There are lots of SOLID design pattern which forms acronym SOLID, read this list of SOLID design
principles for Java programmer to answer this Java interview question.

18. What is difference between Abstraction and Encapsulation in Java?


I have already covered answer of this Java interview question in my previous post as Difference between
encapsulation and abstraction in Java. See there to answer this question.

This was my list of 10 popular design pattern interview question in Java. I have not included MVC
(Model View Controller) design pattern because that is more specific to J2EE and Servlet JSP interview,
but if you are going for any Java interview which demands experience in J2EE than you must prepare
MVC design pattern. That's all on Java design pattern interview question and answers. Please let us
know if you have any other interesting question on Java design pattern

Top 10 tough core Java interview questions answers


programming
tough core Java interview questions and answers
What is tough core java interview question ? Why do people look for tough Java questions before going
for interview? well I don't thing I need to answer these tough questions because its pretty natural to
prepare for tough questions even if you are not expecting tough questions from core Java. If you are
prepare for tough and tricky Java interview question than you feel more confident and answer other Java
interview question with confidence. On the other hand if you are not prepare for tough and tricky core
Java questions than seeing them on Java interview or written test may surprise you. But definition
of tough core Java questions is not universal, same Java question which is easy for one programmer
might be tough for other Java programmer. That's why it's best to prepare your own list of tough interview
questions before appearing on any Java job interview. In this article I am going to share you with my Top
10 tough core Java interview questions and answers, which may help you in Java interview.

10 tough Java interview question and answer

Here is my list of 10 tough or tricky Java interview questions. These questions are mostly from
Core Java and I have not included J2EE questions. As I said you may know answers of these tough Java
question or you may not even find it tough enough to challenge your Java knowledge but once upon a
time these were asked in various Java interview and many programmer including my friends and
colleagues finds them tough to answer.

Why wait and notify is declared in Object class instead of Thread ?


Another tough java question, how can you answer this question if you are not designed Java
programming language. anyway some common sense and deep knowledge of Java programming helps
to answer such tough core java interview question. See this blog post to learn Why wait and notify is
declared in Object class and not in Thread.

Why multiple inheritance is not supported in Java ?


I found this core Java question really tough to answer because your answer may not satisfy Interviewer, in
most cases Interviewer is looking for specific points and if you can bring them, they would be happy. Key
to answer this kind of tough question in Java is to prepare topic well to accommodate any follow-ups.
See Why multiple inheritance is not supported in Java for answer of this tough Java question.

Why Java does not support operator overloading ?


One more similar category of tough Java question. C++ supports operator overloading than why not
Java? this is the argument Interviewer will give to you and some time even say that + operator is
overloaded in Java for String concatenation, Don't be fooled with such arguments. See Why support
operator overloading is not supported in Java for detailed answer of this tricky Java question.

Why String is immutable in Java?


My favorite Java interview question, this is tough, tricky but same time very useful as well. Some
interviewer also ask this question as Why String is final in Java. look at this post for some points which
make sense on Why String is final or immutable in Java

Why char array is preferred to store password than String in Java?


Another tricky Java question which is based on String and believe me there are only few Java
programmer which can answer this question correctly. This is a real tough core Java interview
question and again solid knowledge of String is required to answer this. see Why char array is better than
String for storing password in Java to find out answer of this tough Java question.

How to create thread-safe singleton in Java using double checked locking?


This Java question is also asked as What is thread-safe singleton and how to do you write it. Well
Singleton created with double checked locking before Java 5 was broker and its possible to have multiple
instance of Singleton if multiple thread try to create instance of Singleton at same time. from Java 5 its
easy to create thread safe Singleton using Enum. but if interviewer persist with double checked locking
then you have to write that code for them. remember to use volatile variable. See 10 Java singleton
interview question for more details on this topic.

Write Java program to create deadlock in Java and fix it ?


One of the classical but tough core Java interview question and you are likely to fail if you have not
involved in coding of multi-threaded concurrent Java application. See how to create and prevent
deadlock in Java for complete answer of this tough core Java interview question

What happens if your Serializable class contains a member which is not serializable? How do you
fix it?
Any attempt to Serialize that class will fail with NotSerializableException, but this can be easily
solved by making that variable transient for static in Java. See Top 10 Serialization interview question
answers in Java for more details.

Why wait and notify called from synchronized method in Java?


Another tough core Java question for wait and notify. They are called from synchronized method or
synchronized blockbecause wait and modify need monitor on Object on which wait or notify get called.
See Why wait and notify require synchronized context for complete answer of this tough and tricky Java
multi-threading question.

Can you override static method in Java? if I create same method in subclass is it compile time
error?
No you can not override static method in Java but its not a compile time error to declare exactly same
method in sub class, That is called method hiding in Java. See Can you override static method in
Java for complete answer of this tough Java interview question

Top 10 Tricky Java interview questions and Answers


What is a tricky question? Well, tricky Java interview questions are those questions which has
some surprise element on it. If you try to answer a tricky question with common sense, you will
most likely fail because they require some specific knowledge. Most of the tricky Java
questionscomes from confusing concepts like function overloading and overriding, Multi-
threading which is really tricky to master, character encoding, checked vs unchecked
exceptions and subtle Java programming details like Integer overflow. Most important thing to
answer a tricky Java question is attitude and analytical thinking , which helps even if you don't
know the answer. Anyway in this Java article we will see 10 Java questions which is real tricky
and requires more than average knowledge of Java programming language to answer them
correctly. As per my experience there are always one or two tricky or tough Java interview
question on any core Java or J2EE interviews, so its good to prepare tricky questions from Java
in advance. If I take interview, I purposefully put these kind of question to gauge depth of
candidate's understanding in Java. Another advantage of asking such question is surprise
element, which is key factor to put candidate on some pressure during interviews. Since these
questions are less common, there is good chance that many Java developer doesn't know
about it.

10 Tricky Java interview question - Answered

Here is my list of 10 tricky Java interview questions, Though I have prepared and shared
lot of difficult core Java interview question and answers, But I have chosen them as Top 10
tricky questions because you can not guess answers of this tricky Java questions easily, you
need some subtle details of Java programming language to answer these questions.

Question: What does the following Java program print?

public class Test {


public static void main(String[] args) {
System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
}
}
Answer: This questions is tricky because unlike the Integer, where MIN_VALUE is negative, both
theMAX_VALUE and MIN_VALUE of the Double class are positive numbers.
TheDouble.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least
among all double values. So unlike the obvious answer, this program will print 0.0
becauseDouble.MIN_VALUE is greater than 0. I have asked this question to Java developer
having experience up to 3 to 5 years and surprisingly almost 70% candidate got it wrong.

Question : What will happen if you put return statement or System.exit () on try or catch
block ? Will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that
no matter what, but finally block will always execute. This question challenge that misconcept by
puttingreturn statement in try or catch block or calling System.exit from try or catch block.
Answer of this tricky question in Java is that finally block will execute even if you
put return statement in try block or catch block but finally block won't run if you
call System.exit form try or catch.

Can you override private or static method in Java ?


Another popular Java tricky question, As I said method overriding is a good topic to ask trick
questions in Java. Anyway, you can not override private or static method in Java, if you create
similar method with same return type and same method arguments in child class then it will hide
the super class method, this is known as method hiding. Similarly you cannot override private
method in sub class because it's not accessible there, what you do is create another private
method with same name in child class. See Can you override private method in Java or more
details.

Question: What does the the expression 1.0 / 0.0 will return? will it throw Exception? any
compile time error?
Answer : This is another tricky question from Double class. Though Java developer knows about
double primitive type and Double class, while doing floating point arithmetic they don't pay
enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the
arithmetic calculations involving them. Simple answer to this question is that it will not
throwArithmeticExcpetion and return Double.INFINITY. Also note that the
comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x
is a NaN, one should use the method call Double.isNaN(x) to check if given number
is NaN or not. If you know SQL, this is very close to NULL there.

Does Java support multiple inheritance ?


This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not
Java is the argument Interviewer often give. Answer of this question is much more subtle then it
looks like, because Java does support multiple inheritance of Type by allowing interface to
extend other interfaces, what Java doesn't support is multiple inheritance of implementation.
This distinction also get blur because of default method of Java 8, which now provides
Java, multiple inheritance of behaviour as well. See Why multiple inheritance is not supported in
Java to answer this tricky Java question.

What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of another frequently asked question, How HashMap works in
Java. HashMap is also a popular topic to create confusing and tricky question in Java. Answer
of this question is, if you put the same key again than it will replace the old mapping because
HashMap doesn't allow duplicate keys. Same key will result in same hashcode and will end up
at same position in bucket. Each bucket contains a linked list of Map.Entry object, which
contains both Key and Value. Now Java will take Key object form each entry and compare with
this new key using equals() method, if that return true then value object in that entry will be
replaced by new value. See How HashMap works in Java for more tricky Java questions from
HashMap.

Question : What does the following Java program print?

public class Test {


public static void main(String[] args) throws Exception {
char[] chars = new char[] {'\u0097'};
String str = new String(chars);
byte[] bytes = str.getBytes();
System.out.println(Arrays.toString(bytes));
}
}

Answer: The trikyness of this question lies on character encoding and how String to byte array
conversion works. In this program, we are first creating a String from a character array, which
just has one character '\u0097', after than we are getting byte array from that String and
printing that byte. Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable
to guess that thestr.getBytes() call will return a byte array that contains one element with a
value of -105((byte) 0x97). However, that's not what the program prints and that's why this
question is tricky. As a matter of fact, the output of the program is operating system and locale
dependent. On a Windows XP with the US locale, the above program prints [63], if you run this
program on Linux or Solaris, you will get different values.

To answer this question correctly, you need to know about how Unicode characters are
represented in Java char values and in Java strings, and what role character encoding plays
inString.getBytes(). In simple word, to convert a string to a byte array, Java iterate
through all the characters that the string represents and turn each one into a number of bytes
and finally put the bytes together. The rule that maps each Unicode character into a byte array
is called a character encoding. So It's possible that if same character encoding is not used
during both encoding and decoding then retrieved value may not be correct. When we
call str.getBytes() without specifying a character encoding scheme, the JVM uses the
default character encoding of platform to do the job. The default encoding scheme is operating
system and locale dependent. On Linux, it is UTF-8 and on Windows with a US locale, the
default encoding is Cp1252. This explains the output we get from runing this program on
Windows machines with a US locale. No matter which character encoding scheme is used, Java
will always translate Unicode characters not recognized by the encoding to 63, which represents
the character U+003F (the question mark, ?) in all encodings.

If a method throws NullPointerException in super class, can we override it with a method


which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can
very well throw super class of RuntimeException in overridden method but you can not do same
if its checked Exception. See Rules of method overriding in Java for more details.

What is the issue with following implementation of compareTo() method in Java


public int compareTo(Object o){
Employee emp = (Employee) emp;
return this.id - o.id;
}
where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive.
This Java question becomes tricky when you can't guaranteed that id is positive or negative.
tricky part is, If id becomes negative than subtraction may overflow and produce incorrect
result. See How to override compareTo method in Java for complete answer of this Java tricky
question for experienced programmer.

How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you.
This Java question can be tricky even for experienced and senior programmer, who are not
really exposed to deadlock and race conditions. Key point here is order, if you acquire resources
in a particular order and release resources in reverse order you can prevent deadlock. See how
to avoid deadlock in Javafor a sample code example.

Question : Consider the following Java code snippet, which is initializing two variables
and both are not volatile, and two threads T1 and T2 are modifying these values as
following, both are not synchronized

int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)


x = 1;
bExit = true;

Thread 2 (not synchronized)


if (bExit == true)
System.out.println("x=" + x);
Now tell us, is it possible for Thread 2 to print x=0?

Answer: It's impossible for a list of tricky Java questions to not contain anythign from multi-
threading. This is the simplest one I can get. Answer of this question is Yes, It's possible that
thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or
volatile, bExit=true might come before x=1 in compiler reordering. Also x=1 might not
become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? When I asked
this question to couple of programmers they answer differently, one suggest to make both
thread synchronized on a common mutex, another one said make both variable volatile. Both
are correct, as it will prevent reordering and guarantee visibility. But best answer is you just
need to make bExit as volatile, then Thread 2 can only print x=1. x does not need to be
volatile because x cannot be reordered to come after bExit=true when bExit is volatile.

What is difference between CyclicBarrier and CountDownLatch in Java


Relatively newer Java tricky question, only been introduced form Java 5. Main difference
between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you
can not reuseCountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for
more differences.

What is difference between StringBuffer and StringBuilder in Java ?


Classic Java questions which some people think tricky and some consider very
easy.StringBuilder in Java was introduced in JDK 1.5 and only difference between both of
them is that StringBuffer methods
e.g. length(), capacity() or append() are synchronized while corresponding methods
in StringBuilder are not-synchronized. Because of this fundamental difference,
concatenation of String using StringBuilder is faster than StringBuffer. Actually its considered
bad practice to use StringBuffer any more, because in almost 99% scenario, you perform string
concatenation on same thread. See StringBuilder vs StringBuffer for more differences.

Can you access non static variable in static context?


Another tricky Java question from Java fundamentals. No you can not access non-static
variable from static context in Java. If you try, it will give compile time error. This is actually a
common problem beginners in Java face, when they try to access instance variable inside main
method. Because main is static in Java, and instance variables are non-static, you can not
access instance variable inside main. Read why you can not access non-static variable from
static method to learn more about this tricky Java questions.

Now, its practice time, here are some questions for you guys to answer, these are contributed
by readers of this blog, big thanks to them.
1. When Singleton doesn't remain Singleton in Java?
2. is it possible to load a class by two ClassLoader?
3. is it possible for equals() to return false, even if contents of two Objects are same?
4. Why compareTo() should be consistent to equals() method in Java?
5. When do Double and BigDecimal give different answers for equals() and compareTo()
== 0.
6. How does "has before" apply to volatile work?
7. Why is 0.1 * 3 != 0.3,
8. Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 and which command
arguments change this.
9. What happens when exception is thrown by a Thread?
10. Difference between notify() and notifyAll() call?
11. Difference between System.exit() and System.halt() method?
12. Does following code legal in Java? is it example of method overloading or overriding?
public String getDescription(Object obj){
return obj.toString;
}
public String getDescription(String obj){
return obj;
}
and
public void getDescription(String obj){
return obj;
}

This was my list of Some of the most common tricky question in Java . It's not a bad idea to
prepare tricky Java question before appearing for any core Java or J2EE interview. One or two
open ended or tricky question is quite common in Java interviews.

Hungry for more Java Interview Question and Answer post, check out these articles
18 Java design pattern question asked in interviews
10 Java coding interview question answer for 2 to 4 years experience
Top 21 Most Frequently Asked Java Questions and Answers
You might like:

Recommended by

Posted by Javin Paul at 6:53 AM

Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

Labels: interview questions, java

34 comments:
1.

AnonymousSeptember 10, 2012 at 9:58 PM

Great questions, How about adding tricky questions related to programming exercise ?

Reply

Replies
1.

AnonymousAugust 26, 2013 at 7:58 PM

Top 10 Java Programming Coding Interview Questions Answers


for programmers
Java coding interview questions answers
Java coding interview questions are mostly someprogramming exercises which is asked to be solved in
java programming language in limited time during any core Java or J2EE interview. No matter whether
you have 2 years of experience or 4 years of experience, There is always some coding interview
question in Java programming job you are applying. Actually questions related to Java Coding are
increasingly getting popular on Java interviews for two reasons, first its difficult to crack Java coding
interview questions than answering fact based questions like Why String is immutable in Java or Why
main is static in Java; Second reason of popularity of Coding question in Java interviews is read need of
good developers who are required to do lot of coding in projects rather than doing some maintenance
works. Since Java is front line language for any server side application, and as complexity of business
process and need of performance is increasing, its obvious that amount of coding skill required in Java
programmers are getting increased with every passing days, which effectively mean Java coding
questions are top of any list of core Java interview question. These Coding interview questions are
collected from various Java programming interviews, from friends and colleagues and can be a good
starting point to refresh your coding skills before appearing on any Java interviews. These basics Java
Programs and logical questions can also be a good resources for learning programming and to improve
your problem solving skills in Java.

10 Programming and Coding Interview questions answers in Java

Here are my list of 10 Java coding interview questions and answers, which is good to prepare before
appearing on any Java interviews. As I said Java coding questions are mostly based on programming,
logical analysis and problem solving skill and are on top of any list of tough Java interview questions, so
better to get it right in first place. Any way you may be able to solve and find answers of these Java
coding questions by yourself, but if you stuck do a google, and you can get many alternative ways to
solve these problem. Some times knowing more than one way to solve any programming question or
coding problem in Java also helps to impress interviewer. This list mainly contains basic programs asked
on Interviews.

Write a Java program to replace certain characters from String like


public String replace(String str, char ch)
This is a tricky Java coding interview question is asked in one of the written test my friend had appeared
recently. This Java coding question can be solved in multiple way e.g. by
using charAt() or subString() method, but any approach throws couple of follow-up question e.g.
you may be asked to write two version to solve this coding exercise, one by using recursion and other by
using Iteration. They may also ask you to write JUnit test for this function which means handling null,
empty string etc. By the way this programming question is quite common on technical interviews not just
Java but also C, C++ or Scala, but knowing API definitely helps to produce better solution quickly.

Write a Java program to print Fibonacci series upto 100?


This is one of the most popular coding interview question asked in Java programming language. Even
though, Writing program for Fibonacci series is one of the basic Java program, not every Java developer
get it right in interview. Again interview can ask to solve this programming interview question, by using
recursion or Iteration. This Java programming question also test your problem solving skills and if you
come up with an original solution, that may even help. See here for complete code example of Fibonacci
series in Java

FizzBuzz problem : Write a Java program that prints the numbers from 1 to 50. But for multiples of three
print "Fizz"instead of the number and for the multiples of five print "Buzz". For numbers which are
multiples of both three and five print "FizzBuzz"
This is also one of the classical programming questions, which is asked on any Java programming or
technical interviews. This questions is very basic but can be very trick for programmers, who can't code,
that's why it is used to differentiate programmers who can do coding and who can't. Here is a sample
Java program to solve FizzBuzz problem :

public class FizzBuzzTest{

public static void main(String args[]){

for(int i = 1; i <= 50; i++) {


if(i % (3*5) == 0) System.out.println("FizzBuzz");
else if(i % 5 == 0) System.out.println("Buzz");
else if(i % 3 == 0) System.out.println("Fizz");
else System.out.println(i);
}
}

Write a Comparator in Java to compare two employees based upon there name, departments and
age?
This is pure Java based Coding exercise. In order to solve this Java coding or programming interview
question you need to know What is comparator in Java and How to use compare method in Java for
sorting Object. Sorting is one of the most logical and practical question on technical interview and ability
to sort Java object is must to code in Java. This article help you to solve this Java coding question by
explaining how to sort object in Java using Comparable and Comparator. Just remember
that Comparable has compareTo() method and use to sort object based upon there natural order e.g.
numeric order for number, and alphabetic order for String, while Comparator can define any arbitrary
sorting. A good followup question can also be difference between Comparator and Comparable in
Java, so be ready for that.

Design vending machine in Java which vends Item based upon four denomination of coins and
return coin if there is no Item.
This kind of Java coding interview question appear in written test and I believe if you get it right, you are
almost through the Interview. These kind of problem solving questions in Java are not easy, you need to
design , developer and write JUnit test within 2 to 3 hours and only good Java developers,
with practical coding experience can solve this kind of Java programming question. What helps you is to
keep practicing your coding skill even before interview. See thisprogramming exercise in Java to get
yourself going. I personally like to ask programming questions, which test your object oriented design
skills e.g. designing ATM machine, designing parking lot or implementing logic for Traffic Signal controller.

Write a Java program to check if a number is Armstrong or not ?


Another popular logical coding interview questions in Java, which is based on programming logic. In order
to answer this programming question, you need to know what is Armstrong number, but that is not a
problem because question may specify that and even provide sample input and output. Key thing to
demonstrate is logic to check if a number isArmstrong or not. In most cases, you can not use utility
methods defined by logic and you need to produce logic by yourself by using basic operators and
methods. By the way this is also one of the basic programming questions and I have already provided
a solution for this. I suggest to see this Java program to find Armstrong Number in Java to answer this
coding question

Write a Java program to prevent deadlock in Java ?


Some of the programming or coding interview question is always based on fundamental feature of Java
programming language e.g. multi-threading, synchronization etc. Since writing deadlock proof
code is important for a Java developer, programming questions which requires knowledge of concurrency
constructs becomes popular coding question asked in Java Interviews. Deadlock happens if four
condition is true e.g. mutual exclusion, no waiting, circular wait and no preemption. If you can break any
of this condition than you can create Java programs,which are deadlock proof. One easy way to avoid
deadlock is by imposing an ordering on acquisition and release of locks. You can further check How to fix
deadlock in Java to answer this Java programming questions with coding in Java

Write Java program to reverse String in Java without using API functions ?
Another classic Java programming or coding exercise mostly asked on 2 to 5 years experienced Java
interviews. Despite being simple answering this coding question is not easy, specially if you are not
coding frequently. Its best to prepare this programming question in advance to avoid any embarrassment
during interviews. I suggest to see this post which shows How to reverse String using recursion in Java

Write a Java program to find if a number is prime number or not


One more basic Java program, which made it's way to Interviews. One of the simplest coding question
and also a very popular Java programming exercise. Beauty of these kinds of logical questions is that,
they can really test basic programming skills or a coder, programmer or developer. Not just problem
solving, you can also check there coding style and thought process. By the way. you can check
this article for answer of this Java coding interview question.

How to Swap two numbers without using third variable in Java?


This Java program might require just four lines to code, but it's worth preparing. Most of the programmers
make same kind of mistakes, while writing solution for this program e.g. Integer overflow, they tend to
forget that integer can overflow if it's limit exceeded, which is not very big. Sure shot way to answer this
programming questions is to use XOR trick to swap numbers, as mentioned in that blog post.

Create a Java program to find middle node of linked list in Java in one pass?
Any list of programming questions is incomplete without any questions from linked list, arrays and string,
these three forms bulk of coding questions asked on Java interviews. Trick to solve this problem is to
remember that last node of linked list points to null and you can trade memory with speed. Sometime your
approach to come to two pointer solution really matters, by taking rational steps as mentioned above, you
can sound more intelligent, problem solver and genuine. Quick solution of this programming question can
be found here.

How to find if a linked list contains cycle or not in Java?


Another programming question based on linked list. By the way this coding question is bit tricky than
previous one, but this can also be solved using two pointer approach. If linked list has cycle, than fast
pointer will either catch slow pointer or point to null. See Java program to check if linked list contains loop
in Java for complete solution of this coding interview question.

Implement Producer Consumer design Pattern in Java using wait, notify and notifyAll method in
Java?
Similar to deadlock related programming interview question, this is also used to test programmers ability
to write bug free concurrent programs in Java. This coding questions can be difficult if you haven't used
wait and notify before, you can confuse yourself as hell on different aspect e.g. which condition to check,
on which lock you should synchronized etc. I suggest following here to answer this multithreading based
programming interview question.

Write a Java program to calculate Factorial of a number in Java?


This Java coding interview questions is also based on list of basic Java programs for beginners. As usual,
you better remember how to calculate factorial and how to code solution using loop and recursive method
calls. For complete code solution of this programming question, see Java program to calculate factorial

These are some of the Java coding interview questions and answers, which appears frequently on
Java Programming interviews. I have included links, with some of my blog posts, which discusses
answers of these Java coding question, but you can also find answers by doing google yourself. Please
share what kind of Programming, logical, Problem solving or coding related questions, asked to you in
Java interviews?

Tuesday, July 15, 2014

QuickSort Example in Java using Recursion - Sorting Algorithm


Implementation
Quicksort is one of the very popular sorting algorithm in programming, often used to sort large
list of numbers. Though their are numerous algorithm available to sort list of objects, including
integer, string and floating point number, quicksort is best for general purpose. It's a divide and
conquer algorithm, where we divide the given array with respect to a particular element, known
as 'pivot' such that the lower partition of the array areless than the pivot and upper partition
elements of the array are higher than the pivot. Quicksort is also one of the best example
of recursion. It's naturally recursive, because it sort the large list by dividing into smaller sub-list
and then applying same algorithm on those. Base case of recursion is when list contains either
one or zero element, in that case they are sorted. Quicksort is well ahead with primitive sorting
algorithms e.g. insertion sort, selection sort and bubble sort. Average time complexity of
quicksort is O(nlogn), while in worst case it's performance is similar to bubble sort
i.e. O(n^2). Apparently worst case of quicksort is the best case of insertion sort, where they
have to sort an already sorted list. In this article, we will learnhow to implement quicksort
algorithm in Java using recursion. We will also learn how quicksort works, and how it sorts large
list of unsorted number. In last section, we will see some important things about quicksort.

How QuickSort Algorithm Perform Sorting


An old saying is, a picture is worth more than a thousand words. This is completely true in case
of understanding how sorting algorithm works. In past, I have understood insertion sort,
selection sort and quicksort much better by following a diagram rather then reading about it.
That's why I am sharing this diagram which explains how quicksort algorithm works, how it sort
a list of integers. It's similar to flowchart but doesn't use the notation flowchart uses, instead it
practically shows how sorting happens. Once you go through this diagram, read the
explanation, it will make more sense.
As I told before QuickSort is a recursive algorithm, it divides the big list into smaller list around
pivot until those lists are individually sorted. First step of Quicksort algorithm is to determine
pivot, it's general practice to choose middle element of array as pivot, but you are free to choose
any index. Now you have two list, next step is to ensure that left partition only contains
numbers less than pivot and right partition only contains numbers greater than pivot. We start
pointer from left and right of pivot, and as soon as left pointer encounter 4, it stops because 4 is
greater than 3. Similarly, right pointer stops at 3 because all numbers on right side of the list is
greater than 3. Now it's time to swap, so 3 takes place of 4 and vice-versa. Now, we move
pointer to one more step, since 2 > 3, left pointer shifts but since 4 > 3, it stopped. Since left
point is also past right pointer it stopped. Now if we repeat this process one more time, list will
be sorted.

Concept of Pivot and Partition

Though we often select middle element of array as pivot, there is no such there is no such rule
and pivot can be any element of the given array. You can even consider the first element as the
pivot in every partition. It's experienced that choice of pivot effects the distribution of the
elements in partitioning and affects the complexity of the quicksort algorithm. As per rule of
partition, numbers in lower partition should be less than the pivot and upper partition numbers
should be higher than the pivot. Running time of partition logic is linear.

Complexity of Quicksort Algorithm:

On an average Quicksort Algorithm has the complexity of O(nlogn) and in the worst case it
has O(n) when the elements of the input array are already sorted in ascending or descending
order. Good thing about Quicksort is that it's an in place algorithm, which means it does not
takes any additional space, except those used by method stack. By the way, there are some
tricks to improve performance of quicksort, even in worst case. As suggested in one of the
best algorithm design book, The Algorithm Design Manual, from Steven Skiena, you can apply
following recommendation to improve your quicksort algorithm implementation.

1) Randomization
You can avoid worst case performance of O(n) when sorting nearly-sorted data by random
permutation of keys. Though it incur some cost of permutation but still gives better performance
than O(n)

2) Leave small sub-arrays for Insertion sort


finish Quicksort recursion and switch to insertion sort when fewer then 20 elements:

By the way, there is a drawback of using recursion to implement quicksort algorithm, It will not
scale, because JVM has no tail call optimization, it will simply grow the method call stack to
something proportional to the array to sort, and it will fail for very large array.

Java Program to Sort Integer Array using QuickSort Algorithm

Here is our recursive implementation of QuickSort sorting algorithm. We have used it to sort an
array of randomly distributed integers. We have two set of input, one which doesn't contain any
repeated number and other which contains duplicates. Logic of quicksort is encapsulated in
methodrecursiveQuickSort(int[] array, int startIdx, int endIdx) and partition(int[]
array,int left, int right), which implements partitioning logic. In order to hide
implementation details, we have only exposed a convenient static utility method
called quickSort(int[] array), which takes an integer array and sort that in-place.

package test;

import java.util.Arrays;
/**
* Java program to Sort integer array using QuickSort algorithm using recursion.
* Recursive QuickSort algorithm, partitioned list into two parts by a pivot,
* and then recursively sorts each list.
* @author Javin Paul
*/
public class QuickSort{

public static void main(String args[]) {

int[] input = { 23, 31, 1, 21, 36, 72};


System.out.println("Before sorting : " + Arrays.toString(input));
quickSort(input); // sort the integer array using quick sort algorithm
System.out.println("After sorting : " + Arrays.toString(input));

// input with duplicates


int[] withDuplicates = { 11, 14, 16, 12, 11, 15};
System.out.println("Before sorting : " + Arrays.toString(withDuplicates));
quickSort(withDuplicates); // sort the integer array using quick sort algorithm
System.out.println("After sorting : " + Arrays.toString(withDuplicates));
}

/**
* public method exposed to client, sorts given array using QuickSort
* Algorithm in Java
* @param array
*/
public static void quickSort(int[] array) {
recursiveQuickSort(array, 0, array.length - 1);
}

/**
* Recursive quicksort logic
*
* @param array input array
* @param startIdx start index of the array
* @param endIdx end index of the array
*/
public static void recursiveQuickSort(int[] array, int startIdx, int endIdx) {

int idx = partition(array, startIdx, endIdx);

// Recursively call quicksort with left part of the partitioned array


if (startIdx < idx - 1) {
recursiveQuickSort(array, startIdx, idx - 1);
}

// Recursively call quick sort with right part of the partitioned array
if (endIdx > idx) {
recursiveQuickSort(array, idx, endIdx);
}
}

/**
* Divides array from pivot, left side contains elements less than
* Pivot while right side contains elements greater than pivot.
*
* @param array array to partitioned
* @param left lower bound of the array
* @param right upper bound of the array
* @return the partition index
*/
public static int partition(int[] array, int left, int right) {
int pivot = array[left]; // taking first element as pivot

while (left <= right) {


//searching number which is greater than pivot, bottom up
while (array[left] < pivot) {
left++;
}
//searching number which is less than pivot, top down
while (array[right] > pivot) {
right--;
}

// swap the values


if (left <= right) {
int tmp = array[left];
array[left] = array[right];
array[right] = tmp;

//increment left index and decrement right index


left++;
right--;
}
}
return left;
}
}

Output:
Before sorting : [23, 31, 1, 21, 36, 72]
After sorting : [1, 21, 23, 31, 36, 72]
Before sorting : [11, 14, 16, 12, 11, 15]
After sorting : [11, 11, 12, 14, 15, 16]

Things to know about QuickSort Algorithm in Java

As I said, QuickSort is one of the most popular sorting algorithm between programmers, may be
justnext to Bubble sort, which is ironically worst algorithm to sort large list of numbers. But one
thing is common between QuickSort and Bubble Sort, do you know what? In worst case both
have complexity of O(n^2).

1) QuickSort is a divide and conquer algorithm, which means it sort a large array of numbers by
dividing them into smaller array and then individually sorting them (conquer).

2) Average case complexity of Quicksort is O(n log(n)) and worst case complexity of
Quicksort is O(n).
3) Quicksort is a comparison sort and, in efficient implementations, it's not a stable sort, which
means equal numbers may not retain their original position after sorting.

4) Quicksort algorithm can be implemented in-place, which means no additional space will be
required. This makes it suitable to sort large array of numbers.

5) Arrays.sort() method in Java use quicksort to sort array of primitives e.g. array of
integers or float and uses Mergesort to sot objects e.g. array of String.

That's all about how to implement QuickSort algorithm in Java. QuickSort is one of the fast
and efficient sorting algorithm, perfect for sorting large arrays, but some programmer find it
extremely hard to understand. One reason of this could be that because quicksort is in-place
algorithm due to which programmers find it bit confusing, but it's very efficient. Otherwise if you
choose simplicity you can always implement it in other ways.

You might also like