Top 18 Java Design Pattern Interview Questions Answers For Experienced
Top 18 Java Design Pattern Interview Questions Answers For Experienced
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.
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.
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.
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.
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.
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.
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
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
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.
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.
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
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 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.
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.
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.
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.
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;
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.
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
34 comments:
1.
Great questions, How about adding tricky questions related to programming exercise ?
Reply
Replies
1.
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.
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 :
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 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
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.
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.
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?
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.
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)
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.
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 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) {
// 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
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]
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.