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

1000 Java Interview Questions-3

1) The ++ operator is not thread-safe in Java as it involves multiple instructions that can overlap between threads, potentially causing issues. 2) Non-static variables cannot be accessed from a static context like the main method. An instance of the object must be created to access instance variables. 3) We can override a method that throws a checked exception to throw RuntimeException, but not the other way around.

Uploaded by

Yannick TCHATO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

1000 Java Interview Questions-3

1) The ++ operator is not thread-safe in Java as it involves multiple instructions that can overlap between threads, potentially causing issues. 2) Non-static variables cannot be accessed from a static context like the main method. An instance of the object must be created to access instance variables. 3) We can override a method that throws a checked exception to throw RuntimeException, but not the other way around.

Uploaded by

Yannick TCHATO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 250

414.

Is ++ operation thread-safe in
Java?

No, ++ operator is not a thread safe operation. It involves multiple


instructions like- reading a value, incrementing it and storing it back
into memory. These instructions can overlap between multiple
threads. So it can cause issues in multi-threading.
415. How can you access a non-
static variable from the static context?

We cannot access a non-static variable from the static context in


Java. If you write a code like that, then you will get compile time
error. It is one of the most common problems for beginner Java
programmers, when they try to access instance variable inside the
main method in a class.

Since main method is static in Java, and instance variables are non-
static, we cannot access instance variable inside main. The solution
is to create an instance of the object and then access the instance
variables.
416. Let say there is a method that
throws NullPointerException in the
superclass. Can we override it with a
method that throws
RuntimeException?

This question is checking your understanding of the concepts of


method overloading and overriding in Java.

We can throw superclass of RuntimeException in an overridden


method, but we cannot do the same if it is a checked Exception.
417. How can you mark an array
volatile in Java?
If you know multi-threading well then you can easily answer it.

We can mark an array volatile in Java. But it makes only the


reference to array volatile, not the whole array.

If one thread changes the reference variable to point to another


array, then it will provide a volatile guarantee. But if multiple
threads are changing individual array elements, they won't be having
same reference due to the reference itself being volatile.
418. What is a thread local variable
in Java?

Thread-local variable is a variable restricted to a specific thread. It


is like thread's own copy of variable that is not shared among
multiple threads.
Java provides ThreadLocal class to support thread-local variables.
To achieve thread-safety, you can use it. To avoid any memory leak,
it is always good to remove a thread-local variable, once its work
is done.
419. What is the difference between
sleep() and wait() methods in Java?

In Java, we use these methods to pause currently running thread.


There is a simple difference between these.

sleep() is actually meant for short pause because it doesn't release


lock.

wait() is meant for conditional wait and it can release a lock that
can be acquired by another thread to change the condition on which
it is waiting.
420. Can you create an Immutable
object that contains a mutable object?

In Java, it is possible to create an Immutable object that contains a


mutable object.

We should not share the reference of the mutable object, since it is


inside an immutable object. Instead, we can return a copy of it to
other methods.
421. How can you convert an Array
of bytes to String?

You can convert an Array of bytes to String object by using the


String constructor that accepts byte[]. We need to make sure that
right character encoding is used. Else we may get different results
after conversion.
422. What is difference between
CyclicBarrier and CountDownLatch
class?

CyclicBarrier and CountDownLatch classes were introduced from


Java 5.

We can reuse CyclicBarrier even if it is broken, but we cannot reuse


CountDownLatch in Java.
423. What is the difference between
StringBuffer and StringBuilder?

StringBuilder was introduced in Java 5. The main difference


between both of them is that StringBuffer methods e.g. length(),
capacity(), append() are synchronized. But corresponding methods
in StringBuilder are not synchronized.

Due to this difference, concatenation of String using StringBuilder is


faster than StringBuffer. Now it is considered bad practice to use
StringBuffer, because, in most of the scenarios, we perform string
concatenation in the same thread.
424. Which class contains clone
method? Cloneable or Object class?

It is a very basic trick question. clone() method is defined in Object


class. Cloneable is a marker interface that doesn't contain any
method.
425. How will you take thread dump
in Java?
There are platform specific commands to take thread dump in Java.

In Linux/Unix, just use kill -3 PID, where PID is the process id of


Java process. It will give the thread dump of Java process.

In Windows, press Ctrl + Break. This will instruct JVM to print


thread dump in standard out or err. It can also go to console or log
file depending upon your application configuration.
426. Can you cast an int variable
into a byte variable? What happens if
the value of int is larger than byte?

An int is 32 bit in Java. But a byte is just 8 bit in Java. We can cast
an int to byte. But we will lose higher 24 bits of int while casting.
Because a byte can hold only first 8 bits of int. Remaining 24 bits
(32-8 = 24) will be lost.
427. In Java, can we store a double
value in a long variable without
explicit casting?

No, we cannot store a double value into a long variable without


casting it to long. The range of double is more than that of long. So
we need to type cast.

To answer this question, just remember which one is bigger


between double and long in Java.
428. What will this return 5*0.1 ==
0.5? true or false?

The answer is false because floating point numbers can not be


represented exactly in Java, so 5*0.1 is not same as 0.5.
429. Out of an int and Integer,
which one takes more memory?

An Integer object takes more memory than an int in Java. An Integer


is an object and it stores meta-data overhead about the object. An
int is a primitive type so its takes less memory and there is no meta-
data overhead.
430. Can we use String in the switch
case statement in Java?

Yes. From Java 7 onwards, String can be used in switch case


statement. This gives convenience to programmer. But internally
hash code of String is used for the switch statement.
431. Can we use multiple main
methods in same class?
Yes. You can have multiple methods with name main in the same
class. But there should be only one main method with the signature
public static void main(String[] args). JVM looks for main with this
signature only. Other methods with name main in same class are just
ignored.
432. When creating an abstract
class, is it a good idea to call abstract
methods inside its constructor?

No, we should avoid calling abstract methods in the constructor of


an abstract class. Because, it can restrict how these abstract
methods can be implemented by child classes.

Many IDE give “Overridable method call in constructor” warning


for such implementation.

This is a problem of object initialization order. The superclass


constructor will run before the child class constructor. It means
child class is not yet initialized. But due to presence of overridden
method in superclass, the overridden method of subclass is called
when the subclass is not fully initialized.
433. How can you do constructor
chaining in Java?

When we call one constructor from another constructor of the same


class, then it is known as constructor chaining in Java. When you
have multiple overloaded constructors in a class, you can do
constructor chaining.
434. How can we find the memory
usage of JVM from Java code?
We can use memory management related methods provided in
java.lang.Runtime class to get the free memory, total memory and
maximum heap memory in Java.

By using these methods, you can find out how much of the heap is
used and how much heap space still remains.

Runtime.freeMemory() returns amount of free memory in bytes.


Runtime.totalMemory() returns total memory in bytes.
Runtime.maxMemory() returns maximum memory in bytes.
435. What is the difference between
x == y and x.equals(y) expressions in
Java?
The x == y expression does object reference matching if both a and
b are an object and only returns true if both are pointing to the same
object in the heap space.

The x.equals(y) expression is used for logical mapping and it is


expected from an object to override this method to provide logical
equality.

Eg. A Book object may be logically equal to another copy of same


Book, but it is a different object which will be false while doing x
== y.
436. How can you guarantee that
the garbage collection takes place?

No. We cannot guarantee the garbage collection in Java. Java


documentation explicitly says that GarbageCollection is not
guaranteed.

You can call System.gc() to request garbage collection, however,


that's what it is - a request. It is upto GC's discretion to run.
437. What is the relation between
x.hashCode() method and x.equals(y)
method of Object class?

x.hashCode() method returns an int hash value corresponding to an


object instance.

It is used in hashCode based collection classes like Hashtable,


HashMap, LinkedHashMap etc.

hashCode() method is also related to equals() method.

As per Java specification, two objects which are equal to each


other using equals() method must have same hash code.

Therefore, two objects with same hashCode may or may not be


equal to each other. But two equal objects should have same hash
code.
438. What is a compile time
constant in Java?

A compile time constant is public static final variable. The public


modifier is optional here. At compile time, they are replaced with
actual values because compiler knows their value up-front and it
also knows that it cannot be changed during run-time. So they are
constants.
439. Explain the difference between
fail-fast and fail-safe iterators?
The main difference between fail-fast and fail-safe iterators is
whether or not the collection can be modified while it is being
iterated.

Fail-safe iterators allow modification of collection in an iteration


task. But fail-fast iterators do not allow any modification to
collection during iteration.

During iteration, fail-fast iterators fail as soon as they realize that


the collection has been modified. Modification can be addition,
removal or update of a member. And it will throw a
ConcurrentModificationException.
Eg. ArrayList, HashSet, and HashMap are fail-fast.

Fail-safe iterators operate on a copy of the collection. Therefore


they do not throw an exception if the collection is modified during
iteration.
Eg. ConcurrentHashMap, CopyOnWriteArrayList are fail-safe.
440. You have a character array
and a String. Which one is more
secure to store sensitive data (like
password, date of birth, etc.)?
Short answer is, it is safe to store sensitive information in character
array.

In Java, String is immutable and it is stored in the String pool. Once


a String is created, it stays in the pool in memory until it is garbage
collected. You have no control on garbage collection. Therefore,
anyone having access to a memory dump can potentially extract the
sensitive data and use it.

Whereas, if you use a mutable object like a character array, to store


the value, you can set it to blank once you are done with it. Once it
is made blank it cannot be used by anyone else.
441. Why do you use volatile
keyword in Java?
The volatile keyword guarantees global ordering on reads and
writes to a variable. This implies that every thread accessing a
volatile field will read the variable’s current value instead of using
a cached value.

By marking the variable volatile, the value of a variable is never


cached thread-locally. All reads and writes will go straight to main
memory of Java.
442. What is the difference between
poll() and remove() methods of Queue
in Java?
It is a basic question to know the understanding of Queue data
structure. Both poll() and remove() methods remove and return the
head of the Queue.

When Queue is empty, poll() method fails and it returns null, but
remove() method fails and throws Exception.
443. Can you catch an exception
thrown by another thread in Java?
Yes, it can be done by using Thread.UncaughtExceptionHandler.

Java Documentation says “When a thread is about to terminate due


to an uncaught exception the Java Virtual Machine will query the
thread for
its UncaughtExceptionHandler usingThread.getUncaughtExceptionHandler()
will invoke the handler's uncaughtException method, passing the
thread and the exception as arguments.”
444. How do you decide which type
of Inner Class – Static or Non-Static
to use in Java?
An inner class has full access to the fields and methods of the
enclosing class. This is convenient for event handlers, but comes at
a cost. Every instance of an inner class retains and requires a
reference to its enclosing class.

Due to this cost, there are many situations where static nested
classes are preferred over inner classes. When instances of the
nested class outlive instances of the enclosing class, the nested
class should be static to prevent memory leaks.

At times, due to their “hidden” reference to enclosing class, Inner


classes are harder to construct via reflection.
445. What are the different types of
Classloaders in Java?
Java Classloader is the part of the Java Runtime Environment (JRE)
that loads classes on demand into Java Virtual Machine (JVM).

When the JVM is started, three types of class loaders are used:

1. Bootstrap Classloader: It loads core java API file rt.jar classes


from folder.
2. Extension Classloader: It loads jar files from lib/ext folder.
3. System/Application Classloader: It loads jar files from path
specified in the CLASSPATH environment variable.

Classes may be loaded from the local file system, a remote file
system, or even the web.
446. What are the situations in
which you choose HashSet or
TreeSet?
HashSet is better than TressSet in almost every way. It gives O(1)
for add(), remove() and contains() operations. Whereas, TressSet
gives O(log(N)) for these operations.

Still, TreeSet is useful when you wish to maintain order over the
inserted elements or query for a range of elements within the set.

We should use TreeSet when we want to maintain order. Or when


there are enough read operations to offset the increased cost of
write operations.
447. What is the use of method
references in Java?
Java 8 has introduced Method references. It allows constructors and
methods to be used as lambdas.

The main uses of Method reference are to improve code


organization, clarity and terseness.
448. Do you think Java Enums are
more powerful than integer
constants?
Yes. Java Enums provide many features that integer constants
cannot. Enums can be considered as final classes with a fixed
number of instances. Enums can implement interfaces but cannot
extend another class.

While implementing the strategy pattern, we can use this feature of


Enums. Especially, when the number of strategies is fixed.

You can also attach meta-data to enum values in Java. Also enum
values are typesafe, where as integer constants are not.

You can also define custom behavior in enum values.


449. Why do we use static
initializers in Java?
In Java, a static initializer can run code during the initial loading of
a class and it guarantees that this code will only run once. Also the
static code will finish running before a class can be accessed in any
way.

Initializing static members from constructors is more work. You


have to make sure that every constructor does this. You need to
maintain a flag to mark the static work when it is done. You may
have to think about synchronization or races conditions for work in
static block not initialized from static context.
450. Your client is complaining that
your code is throwing
NoClassDefFoundError or
NoSuchMethodError, even though
you are able to compile your code
without error and method exists in
your code. What could be the reason
behind this?
Sometimes we upgrade our libraries even with same method name.
But we forget to let the client know about the new version. Due this
different in version, we get NoClassDefFoundError or
NoSuchMethodError at runtime when one library was not
compatible with such an upgrade.

Java build tools and IDEs can also produce dependency reports that
tell you which libraries depend on that JAR. Mostly, identifying and
upgrading the library that depends on the older JAR resolve the
issue.
451. How can you check if a String
is a number by using regular
expression?
Regex is a powerful tool for matching patterns and searching
patterns.

A numeric String can only contain digits i.e. 0 to 9. It can also


contain + and - sign at start of the String. We can create a regular
expression for these two rules. One simple example is as follows:

Pattern pattern = Pattern.compile(".*\\D.*");


452. What is the difference between
the expressions String s =
"Temporary" and String s = new
String("Temporary ")? Which one is
better and more efficient?
In general, String s = " Temporary " is more efficient to use than
String s = new String("Temporary ").

In case of String s = " Temporary ", a String with the value


“Temporary” is created in String pool. If another String with the
same value is created (e.g., String s2 = " Temporary "), it will
reference the same object in the String pool.

But, when you use String s = new String("Temporary "), Java


creates a String with the value “Temporary” in the String pool.
Also, that String object is then passed to the constructor of the
String Object i.e. new String("Temporary "). And this call creates
another String object (not in the String pool) with that value.

Therefore, each such call creates an additional String object. E.g.


String s2 = new String("Temporary ") creates an extra String object,
rather than just reusing the same String object from the String pool.

So String s = “Temporary” is always an efficient way.


453. In Java, can two equal objects
have the different hash code?
No. It is not possible for two equal objects to have different
hashcode. But two objects with same hashcode may or may not be
equal.
454. How can we print an Array in
Java?
We can print an array by using methods of Arrays class. We can
either use Arrays.toString() method or we can use
Arrays.deepToString() method.

Since array doesn't implement toString() method by itself, just


passing an array to System.out.println() will not print its contents.
But we can use Arrays.toString() to print each element of an array.
455. Is it ok to use random numbers
in the implementation of hashcode()
method in Java?
No. The hashcode of an object should be always same. If you use
random number in hashcode() method, then you may get a different
value of hashcode for same object. This will break the hashcode
contract.
456. Between two types of
dependency injections, constructor
injection and setter dependency
injection, which one is better?
Constructor injection guarantees that a class will be initialized with
all its dependencies during creation. But setter injection provides
flexibility to set an optional dependency.

If we are using an XML file to describe dependencies, the setter


injection is more readable.

In general, it is a good practice to use constructor injection for


mandatory dependencies and use setter injection for optional
dependencies.
457. What is the difference between
DOM and SAX parser in Java?
In Java, Document Object Model (DOM) parser loads the whole
XML into memory and creates a tree based on DOM model. This
helps it in quickly locating the nodes, and making a change in the
structure of XML.

On the other hand, Simple API for XML (SAX) parser is an event
based parser. It doesn't load the whole XML into memory. Due to
this reason DOM is faster than SAX but require more memory and
is not suitable to parse large XML files.
458. Between Enumeration and
Iterator, which one has better
performance in Java?
Enumeration interface is a read-only interface. It has better
performance than Iterator. It is almost twice as fast as compared to
an Iterator. It also uses very less memory. Also Enumeration does
not have remove() method.

On the other hand, Iterator interface is safer than Enumeration, since


it can check whether a collection is modified or not during iteration.
If a collection is altered while an Iterator is iterating, then it throws
ConcurrentModificationException.
459. What is the difference between
pass by reference and pass by value?
Whenever an object is passed by value, it means that a copy of the
object is passed. Even if changes are made to that object, it doesn’t
affect the original value.

Whenever an object is passed by reference, it means that the actual


object is not passed, rather a reference of the object is passed.
Therefore, any changes made by an external method, are also
reflected in the actual object and its reference.
460. What are the different ways to
sort a collection in Java?
The most popular way to sort a collection in Java is by calling
Collections.sort() method. You can provide your custom
Comparator to sort() method for sorting the data in your custom
way.

The other way is to use a Sorted collection like TreeSet or TreeMap


that stores the information in a sorted order and then you can
convert it to a List.
461. Why Collection interface
doesn’t extend Cloneable and
Serializable interfaces?
Collection interface just specifies groups of objects known as
elements. Each concrete implementation of a Collection can choose
its own way of how to maintain and order its elements.

Some collections may allow duplicate keys, while other collections


may not.

A lot of collection implementations have clone method. But many do


not. It is not worthwhile to include it in all, since Collection is an
abstract representation. What matters is the concrete
implementation.

Cloning and serialization come into picture while doing concrete


implementation. Therefore, the concrete implementations of
collections should decide how they can be cloned or serialized.
462. What is the difference between
a process and a thread in Java?
A process is simply an execution of a program.

A Thread is a single execution sequence within a process.

A process may contain multiple threads. A Thread is also called as


a lightweight process.
463. What are the benefits of using
an unordered array over an ordered
array?
In an ordered array the search time has time complexity of O(log n).
Whereas, in an unordered array, search time complexity is O (n).

In an ordered array, the insert operation has a time complexity of


O(n). Whereas, the insertion operation for an unordered array takes
constant time of O(1).

Therefore, when we have more writes than reads, it is preferable to


use an unordered array.
464. Between HashSet and TreeSet
collections in Java, which one is
better?
A HashSet is Implemented using a HashTable. Therefore, its
elements are stored in a random order. The add(), remove(), and
contains() methods of a HashSet have constant time complexity
O(1).

A TreeSet is implemented using a tree data structure. The elements


in a TreeSet are sorted in a natural order. Therefore, add(),
remove(), and contains() methods have time complexity of O(logn).

So from performance perspective, HashSet has better performance


than TreeSet. But if you want to store elements in a natural sorting
order, then TreeSet is a better collection.
465. When does JVM call the
finalize() method?
JVM instructs the Garbage Collector to call the finalize method, just
before releasing an object from the memory. A programmer can
implement finalize() method to explicitly release the resources held
by the object. This will help in better memory management and
avoid any memory leaks.
466. When would you use Serial
Garabage collector or Throughput
Garbage collector in Java?
The Serial Garbage collector is used for small applications that
require heap memory upto 100 MB.

The Throughput Garbage collector is used in medium to large size


Java applications.
467. In Java, if you set an object
reference to null, will the Garbage
Collector immediately free the
memory held by that object?
No. JVM decides to run the Garbage Collector whenever it is low
on memory. When Garbage Collector runs, it looks for objects that
are available for garbage collection and then frees the memory
associated with this object.

So just setting an Object reference null makes it eligible for


Garbage Collection, but it does not immediately free the memory.
468. How can you make an Object
eligible for Garbage collection in
Java?
To make an Object eligible for Garbage collection, just make sure
that it is unreachable to the program in which it is currently defined
/ created / used. You can set the object reference to null and make
sure no other object refers it. Once the object cannot be reached,
Garbage Collection can clean it during the next run.
469. When do you use Exception or
Error in Java? What is the difference
between these two?
Throwable class is the superclass of Exception and Error classes in
Java.

When you want to catch the exceptional conditions that your


program can create or encounter, then use the Exception class or
subclass of Exception.

When you come across situations that are unexpected then use Error
class in Java. Also recovering from Error is not possible in most of
cases. So it is better to terminate the program.
470. What is the advantage of
PreparedStatement over Statement
class in Java?
PreparedStatements are precompiled statements for database
queries. Due to this their performance is much better. Also, we can
reuse PreparedStatement objects with different input values to the
same query.

Where as, Statement class does not provide these features.


471. In Java, what is the difference
between throw and throws keywords?
When we want to raise an exception in our code, we use the throw
keyword with the name of the exception to be raised.

Where as, throws keyword is used in method declaration. Throws


keyword tells us the Exception that can be thrown by this method.
Any caller of this method should be prepared to expect this
Exception.

Another minor difference is that throw is used only with one


exception, but throws can be used with comma-separated list of
multiple exceptions.
472. What happens to the Exception
object after the exception handling is
done?
Once the exception handling is complete, the Exception object is not
reachable. Then it is garbage collected in the next run of Garbage
Collector.
473. How do you find which client
machine is sending request to your
servlet in Java?
We can use the ServletRequest class to find the IP address or host
name of the client machine.

There are methods getRemoteAddr() to get the IP address of the


client machine and getRemoteHost() to get the host name of the
client machine.
474. What is the difference between
a Cookie and a Session object in
Java?
Both Cookie and Session are used during communication between
Client and Server. The Client can disable a Cookie. Due to which
the Web server cannot send a cookie. But a client cannot disable a
session. So a Session always works irrespective of any setting at
the client side.

Also a Session can store any Java object. But the Cookie can only
store small information in a String object.
475. Which protocol does Browser
and Servlet use to communicate with
each other?
HTTP protocol. The Browser and Servlet communicate with each
other by using the HTTP protocol.
476. What is HTTP Tunneling?
There are many network communication protocols on the Internet.
But HTTP is the most popular among them. HTTP Tunneling is a
technique in which HTTP or HTTPS protocol encapsulated the
communication done by any other type of protocol. The masking of
other protocol requests as HTTP requests is known as HTTP
Tunneling.
477. Why do we use JSP instead of
Servlet in Java?
Since JSP pages are dynamically compiled into servlets, the
programmers can easily make updates to the presentation layer
code.

For better performance, JSP pages can be pre-compiled.

Also JSP pages provide flexibility to combine static templates like


HTML or XML snippets.

In addition, programmers can make logic changes at the class level,


without editing the JSP pages that use the class logic.
478. Is empty ‘.java’ file name a
valid source file name in Java?
Yes. You can create a class and store it in a file with name .java.
You can try it yourself, by creating, compiling and running such a
file. It will run correctly.
479. How do you implement Servlet
Chaining in Java?
To implement, Servlet Chaining, there has to be more than one
servlet. The output of one servlet has to be sent to a second servlet.
The output of the second servlet can be sent to a third servlet, and
so on. In this way, a chain of servlets is formed to complete a task.

The last servlet in the chain will be responsible for sending final
response to client.
480. Can you instantiate this class?
public class A
{
A a = new A();
}

No, this class cannot be instantiated, since it will result in


recursively calling its constructor.
481. Why Java does not support
operator overloading?
Java supports Method overloading but does not support operator
overloading. It would make the design more complex by adding
operator loading. Also it will make more complex compiler.

One more reason is that, it will reduce the performance of JVM by


operator overloading, since JCM has to do extra work to find the
real meaning of overloaded operators at run time.
482. Why String class is Immutable
or Final in Java?

Since String objects are cached in a String pool, it makes sense to


make the String immutable. The cached String literals are shared
between multiple clients. And there is a possibility that one client's
action may affect another client’s access to String pool.

String is also used as a parameter in many Java classes. Eg. You can
pass hostname, port number as String while opening a network
connection. If any one can modify your copy of the String, it can
change the hostname. Due to this reason, it makes sense to make
String final as soon as it is created.
483. What is the difference between
sendRedirect and forward methods?
When you use sendRedirect method, it creates a new request. When
you use the forward method, it just forwards a request to a new
target.

In case of sendRedirect, the previous request scope objects are not


available, because it creates a new request.

In case of forward method, the previous request scope objects are


available after forwarding.

Also the sendRedirect method is considered slower than the


forward method.
484. How do you fix your
Serializable class, if it contains a
member that is not serializable?
If you want to make a class Serializable, but find that this class
contains members that are not Serializable, then you have to mark
those members as transient. This will ensure that this member is not
persisted to a stream of bytes during Serialization.

Therefore, Transient keyword of Java comes to help in this


scenario.
485. What is the use of run time
polymorphism in Java?
During the run time the behavior of an Object can change based on
its run time state. Due to this run time polymorphism is introduced
in Java. If you override a method in a child class, then you are
providing run time polymorphism. Nothing will happen at the
compile time. But at the run time, JVM decides which method will
be called based on the class of the Object.
486. What are the rules of method
overloading and method overriding in
Java?
When we want to overload a method, we need to make sure that the
method name remains same. But method signature can vary in the
number or datatype of arguments or in the order of arguments.

When we want to override a method, we ensure that the method is


not throwing checked exceptions that are new or higher than those
declared by the overridden method. Also we make sure that the
method name, arguments and return type remain the same.

Also we cannot override Static and Final methods in Java.


487. What is the difference between
a class and an object in Java?
A Class is a template or a blue print of an Object to be created. An
Object is an instance of a Class. A Class defines the methods and
member variables. But an Object populates the values of the
member variables.

Therefore a class is a blueprint that you use to create objects. An


object is an instance of a class – it is a concrete 'thing' that you
made using a specific class.

Most of the OOPS concepts are valid only when an Object is


created.
488. Can we create an abstract class
that extends another abstract class?
Yes. An abstract class can extend another abstract class. It does not
need to define the methods of parent abstract class. Only the last
non-abstract class has to define the abstract methods of a parent
abstract class.
489. Why do you use Upcasting or
Downcasting in Java ?
When we want to cast a Sub class to Super class, we use Upcasting.
It is also known as widening. Upcasting is always allowed in Java.

When we want to cast a Super class to Sub class, we use


Downcasting. It is also known as narrowing.

At times, Downcasting can throw the ClassCastException if it fails


the type check.
490. What is the reason to organize
classes and interfaces in a package in
Java?
As the name suggests, a package contains a collection of classes. It
helps in setting the category of a file. Like- whether it is a Data
Access Object (DAO) or an API.

It helps in preventing the collision of Name space.

Also we can introduce access restriction by using package and the


right modifiers on a class and its methods.
491. What is information hiding in
Java?
Information hiding is OOPS concept. In Java you can use
encapsulation to do Information hiding. An object can use the access
modifiers like-public, private, protected to hide its internal details
from another object. This helps in decoupling the internal logic of
an object from outside world.

By using Information hiding, an object can change its internal


implementation without impacting the outside calling client’s code.
492. Why does Java provide default
constructor?
In Java all the interaction takes place between Object instances. To
create an Object instance, JVM needs a constructor. Java does not
enforce the rule on a programmer to define a default constructor for
every class.

Whenever an object has to be created and programmer has not


provided a constructor, Java uses default constructor to create the
object. Default constructor also initializes member variables with
their default values.
493. What is the difference between
super and this keywords in Java?
We use super keyword to access the methods of the super class from
child class.

We use this keyword to access methods of the same class.


494. What is the advantage of using
Unicode characters in Java?
Unicode characters have much larger number of characters in the
specification.

They also contain Asian and non-western European characters.

Most of the modern technologies, websites and browsers support


these Unicode characters.
495. Can you override an
overloaded method in Java?
Yes. Java allows to override an overloaded method, if that method
is not a static or final method.
496. How can we change the heap
size of a JVM?
Java provides the command line parameters to set the heap size for
JVM.
You can specify the values in –Xms and –Xmx parameters. These
parameters stand for initial and maximum heap size of JVM.
497. Why should you define a
default constructor in Java?
In general, Java provides a default constructor with each class. But
there are certain cases when we want to define our own version of
default constructor.

When we want to construct an object with default values, we create


our default constructor.

At times, we can mark the default constructor private. So that any


other class cannot create an instance of our class. This technique is
generally used in Singleton design pattern.
498. How will you make an Object
Immutable in Java?
To make an object immutable follow these two rules. One, do not
use any setter methods that can change the fields of your class. Two,
make the fields final. By following these rules, the member
variables cannot be changed after initialization. This will ensure
that member variables of an Object do not change. And thus the
Object will be considered Immutable.
499. How can you prevent SQL
Injection in Java Code?
In Java, you can use PreparedStatement to prevent SQL injection. In
a PreparedStatement you can pass the precompiled SQL queries
with pre-defined parameters. This helps in checking the type of
parameters to SQL queries. So it protects your code from SQL
injection attacks.
500. Which two methods should be
always implemented by HashMap key
Object?
Any object that we want to use as key for HashMap or in any other
hash based collection data structure e.g. Hashtable, or
ConcurrentHashMap must implement equals() and hashCode()
method.
501. Why an Object used as Key in
HashMap should be Immutable?
The Key object should be immutable so that hashCode() method
always return the same value for that object.

The Hashcode returned by hashCode() method depends on values of


member variables of an object. If an object is mutable, then the
member variables can change. Once the member variables change,
the Hashcode changes. If the same object returns different hash code
at different times, then it is not reliable to be used in the HashMap.

Let say, when you insert the object, the Hashcode is X, the
HashMap will store it in bucket X. But when you search for it the
Hashcode is Y, then HashMap will look for the object in bucket Y.
So you are not getting what you stored.

To solve this, a key object should be immutable.

Although, the compiler does not enforce this rule, a good


programmer always remembers this rule.
502. How can we share an object
between multiple threads?
There are many ways to share same object between multiple
threads. You can use a BlockingQueue to pass an object from one
thread to another thread.

You can also use Exchanger class for this purpose. An Exchanger is
a bidirectional form of a SynchronousQueue in Java. You can use it
to swap the objects as well.
503. How can you determine if your
program has a deadlock?
If we suspect that our application is stuck due to a Deadlock, then
we just take a thread dump by using the command specific to
environment in which your application is running. Eg. In Linux you
can use command kill -3.

In case of deadlock, you will see in thread dump the current status
and stack trace of threads in the JVM, and one or more of them will
be stuck with message deadlock.

Also you can do this programmatically by using the ThreadMXBean


class that ships with the JDK.

If you don't need programmatic detection you can do this via


JConsole. On the thread tab there is a "detect deadlock" button.
Mixed Questions
1. What are Wrapper classes in Java?

Java has concept of Wrapper classes to allow primitive types to be


accessed as objects. Primitive types like boolean, int, double, float
etc. have corresponding Wrappers classes – Boolean, Integer,
Double, Float etc.

Many of these Wrapper classes are in java.lang package.

Java 5.0 has launched the concept of Autoboxing and Unboxing in


Java for Wrapper classes.

E.g.

public class WrapperTest{


public static void main(String args[]){
//Converting int into Integer
int count=50;
Integer i=Integer.valueOf(count);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write
Integer.valueOf(count) internally

System.out.println(count+" "+i+" "+j);


}}
2. What is the purpose of native
method in Java?
The native keyword is used for applying to a method to indicate that
the method is implemented in native code using JNI(Java Native
Interface).

Therefore, native methods allow Java Developer to directly access


platform specific APIs.

Often, native methods are linked to native library.


3. What is System class?

System.class is a final class provided by java.lang package. It


contains several useful class fields and methods.

The purpose of System class is to provide access to system


resources.
4. What is System, out and println in
System.out.println method call?

System is a final class provided by java.lang package.

out refers to PrintStream class and a static member of System class.

println is a method of PrintStream class.


5. What is the other name of Shallow
Copy in Java?

Object Cloning. A Shallow Copy just copies the values of references in a


Class.
6. What is the difference between
Shallow Copy and Deep Copy in
Java?
A Shallow copy just copies the values of the references in the class.
A Deep copy copies the values of the objects as well.
7. What is a Singleton class?

A Singleton class in Java has maximum one instance of the class


present in JVM, all the time. The constructor of this class is written
in such a way that it never creates more than one object of same
class.
8. What is the difference between
Singleton class and Static class?
A static class in Java has only static methods. It is a container of
functions. It is created based on procedural programming design.

Singleton class is a pattern in Object Oriented Design. A Singleton


class has only one instance of an object in JVM. This pattern is
implemented in such a way that there is always only one instance of
that class present in JVM.
JSP
9. What are the implicit objects in
JSP?
JSP has following implicit objects:

1. Request
2. Response
3. Application
4. Exception
5. Page
6. Config
7. Session
10. How will you extend JSP code?

We can extend JSP code by using Tag libraries and Custom actions.
11. How will you handle runtime
exceptions in JSP?

We use Errorpage attribute in JSP to catch runtime exceptions. This


attribute forwards user request to the error page automatically.
12. How will you prevent multiple
submits of a page that come by
clicking refresh button multiple
times?
We can use Post Redirect Get (PRG) pattern to solve the issue of
multiple submission of same data. It works as follows:

First time when a user submits a form to server by POST or GET


method, then we update the state in application database.

Then we send a redirect response to send reply to client.

Then we load a view by using GET command. There is no data is


sent in this. Since this a new JSP page, it is safe from multiple
submits. The code that processes the request is idempotent. So it
does not do same action twice for same request.
13. How will you implement a thread
safe JSP page?
We can use SingleThreadModel Interface to implement a thread safe
JSP page.

We can also add <%@page isThreadSafe=”false” %> directive in


JSP page to make it thread safe.
14. How will you include a static file in
a JSP page?
We can use include directive of JSP to include a Static page in JSP.
In this approach, we use translation phase to include a static page.
We have to specify the URL of the resource to be included as file
attribute in this directive.

E.g. <%@ include file="footer.html" %>


15. What are the lifecycle methods of a
JSP?
A JSP has following lifecycle methods:

1. jspInit(): This method is invoked when the JSP is called


for the first time. We can do initial setup for servicing a
request in this method.

2. _jspService(): This method is used to serve every request


of the JSP.

3. jspDestroy(): Once we remove a JSP from the container,


we call this method. It is used for cleanup of resources like
Database connections etc.
16. What are the advantages of using
JSP in web architecture?
We get following advantages by using JSP in web architecture:

1. Performance: JSP provides very good performance due to


their design of using same code to service multiple
requests.

2. Fast: Since JSP is pre-compiled, server can serve the


pages very fast.

3. Extendable: JSP is based on Java Servlets. This helps in


extending JSP architecture with other Java technologies
like JDBC, JMS, JNDI etc.

4. Design: It is easier to design user interface with JSP, since


it is very close to HTML. UI designers can create a JSP
with mock data and developers can later provide
implementation of dynamic data.
17. What is the advantage of JSP over
Javascript?
In JSP we can write Java code seamlessly. It allows for writing
code that can interact with the rest of the application.

Javascript code is mostly executed at client side. This limits the


tasks that can be done in Javascript code. We cannot connect to
database server from Javascript at the client side.
18. What is the Lifecycle of JSP?

JSP has following lifecycle stages:

1. Compilation: When a request is made for a JSP, the


corresponding JSP is converted into Servlet and compiled.
If there is already a compiled form of JSP and there is not
change in JSP page since last compilation, this stage does
not do anything.

2. Initialization: In this stage, jspInit() method is called to


initialize any data or code that will be later used multiple
times in _jspService() method.

3. Service: In this stage, with each request to JSP,


_jspService() method is called to service the request. This
is the core logic of JSP that generates response for request.

4. Destroy: In this stage, JSP is removed from the


container/server. Just before removal, this stage performs
the cleanup of any resources held by JSP.
19. What is a JSP expression?

A JSP expression is an element of a JSP page that is used to


evaluate a Java expression and convert into a String. This String is
replaced into the locations wherever the expression occurs in JSP
page.

E.g. <%= expression =%>


20. What are the different types of
directive tags in JSP?
JSP has following directive tags:

1. Page: This directive is used for page related attributes. It


can be put anywhere in the JSP page. But by convention we
put it on the top of the page.

E.g.
<%@ page attribute="value" %>

2. Taglib: We can create custom tags in JSP and use these by


taglib directive in a JSP page.

E.g.
<%@ taglib uri=“abc.html” prefix=“tag_prefix” >

3. Include: We use include directive to read a file and merge


its content with the JSP page. This is done during
compilation stage.

<%@ include file="relative url" >


21. What is session attribute in JSP?

Session attribute in JSP is used for HTTP session mechanism. If we


do not want to use HTTP session in JSP, then we set this attribute to
false. If it is set to true, we can use built in session object in JSP.
22. What are the different scopes of a
JSP object?
A JSP object, implicit or explicit, can have one of the following
scopes:

1. Page: In this scope, the object is accessible from the page


where it was created. Important point here is that when a
user refreshes the page, the objects of this scope also get
created again.

2. Request: In request scope, the object is accessible to the


HTTP request that created this object.

3. Session: In this scope, the object is available throughout


the same HTTP session.

4. Application: This is the widest scope. The object is


available throughout the application in which JSP was
created.
23. What is pageContext in JSP?

In JSP, pageContext is an implicit object. This is used for storing


and accessing all the page scope objects of JSP.

It is an instance of the PageContext class from javax.servlet.jsp


package.
24. What is the use of jsp:useBean in
JSP?
We use jsp:useBean to invoke the methods of a Java Bean class.
The Java Bean class has some data and setter/getters to access the
data.

With this tag, container will try to locate the bean. If bean is not
already loaded then it will create an instance of a bean and load it.
Later this bean can be used in expressions or JSP code.
25. What is difference between
include Directive and include Action
of JSP?
Some of the main differences between include Directive and
include Action are as follows:

1. Include directive is called at translation phase to include


content in JSP. Include Action is executed during runtime
of JSP.

2. It is not possible to pass parameters to include directive.


Include action can accept parameters by jsp:param tag.

3. Include directive is just copying of content from another


file to JSP code and then it goes through compilation.
Include action will dynamically process the resource being
called and then include it in the JSP page.
26. How will you use other Java files
of your application in JSP code?
We can use import tag to import a Java file in JSP code. Once a file
is imported, it can be used by JSP code. It is a very convenient
method to use Java classes in JSP code.

For better organization of Java code, we should create a package of


classes that we are planning to use in JSP code.
27. How will you use an existing class
and extend it to use in the JSP?
We can use extends attribute in include tag to use an existing class
and extend it in the current JSP.

E.g.

<%@ include page extends=“parent_class” %>


28. Why _jspService method starts
with _ symbol in JSP?
All the code that we write in a JSP goes into _jspService method
during translation phase. We cannot override this method. Where as
other lifecycle methods jspInit() and jspDestroy() can be
overridden.

It appears that container uses _ symbol to distinguish the method that


cannot be overridden by client code.
29. Why do we use tag library in JSP?

At times we want to create a UI framework with custom tags. In


such a scenario, taglib is a very good feature of JSP. With taglib we
can create tags that can provide custom features.

Taglib is also a nice way to communicate with UI designers who


can use custom tags in the html without going into the details of how
the code is implemented.

Another benefit of taglib is reusability of the code. This promotes


writing code only once and using is multiple times.
30. What is the different type of tag
library groups in JSTL?
JSTL stands for JavaServer Pages Standard Tag Library. In JSTL,
we have a collection of JSP tags that can be used in different
scenarios. There are following main groups of tags in JSTL:

1. Core tags
2. SQL tags
3. Formatting tags
4. XML tags
5. JSTL Functions
31. How will you pass information
from one JSP to another JSP?
We can pass information from one JSP to another by using implicit
objects. If different JSP are called in same session, we can use
session object to pass information from one JSP to another.

If we want to pass information from one JSP to another JSP


included in the main JSP, then we can use jsp:param to pass this
information.
32. How will you call a stored
procedure from JSP?
JSP allows running Java code from a .jsp file. We can call a stored
procedure by using JDBC code.

We can call a CallableStatement from JSP code to invoke a stored


procedure.

If we are using Spring framework, then we can use JdbcTemplate


class to invoke stored procedure from a JSP.
33. Can we override _jspService()
method in JSP?
No, JSP specification does not allow overriding of _jspService
method in JSP. We can override other methods like jspInit() and
jspDestroy().
34. What is a directive in JSP?

JSP directive is a mechanism to pass message to JSP container. JSP


directive does not produce an output to the page. But it
communicates with JSP container.

E.g. <%@include ..%> directive is used for telling JSP container


to include the content of another file during translation of JSP.

There can be zero or more attributes in a directive to pass


additional information to JSP container.

Some of the important directives in JSP are: page, include and


taglib.
35. How will you implement Session
tracking in JSP?
We can use different mechanisms to implement Session tracking
JSP. Some these mechanisms are as follows:

1. Cookies: We can use cookie to set session information and


pass it to web client. In subsequent requests we can use the
information in cookie to track session.

2. Hidden Form Field: We can send session id in a hidden


field in HTML form. By using this we can track session.

3. Session object: We can use the built in session object to


track session in JSP.

4. URL Rewriting: We can also add session id at the end of


a URL.

Like- www.abcserver.com?sessionid=1234
36. How do you debug code in JSP?

In simplest form we can write logger statements or


System.out.println() statements to write messages to log files. When
we call a JSP, the log messages get written to logs. With useful
information getting logged we can easily debug the code.

Another option in debugging is to link JSP container with an IDE.


Once we link IDE debugger to JSP Engine, we can use standard
operations of debugging like breakpoint, step through etc.
37. How will you implement error
page in JSP?
To implement an error-handling page in JSP, we first create a JSP
with error page handling information. In most of the cases we
gracefully handle error by giving a user-friendly message like
“Sorry! There is system error. Please try again by refreshing page.”

In this error page, we show user-friendly message to user, but we


also log important information like stack trace to our application log
file.

We have to add parameter isErrorPage=true in page directive of this


page. This tells to JSP container that this is our error page.

<%@page isErrorPage=”true” %>

Now we can use this error page in other JSP where we want to
handle error. In case of an error or exception, these JSP will direct
it to errorPage.

<% page errorPage=”ErrorPage.jsp” %>


38. How will you send XML data from
a JSP?
In general, JSP is used to pass HTML data to web browser. If we
want to send data in XML format, we can easily do it by setting
contentType=”text/xml” in page directive.

E.g. <%@page contentType=”text/xml” %>


39. What happens when we request
for a JSP page from web browser?
When a user calls JSP page from web browser, the request first
comes to web server. Web server checks for .jsp extension of page
and passes the request to JSP container like Tomcat.

The JSP container checks whether it has precompiled JSP class or


not. If this is the first time this JSP is called, then JSP container will
translate JSP into a servlet and compiles it.

After compiling, JSP code if loaded in memory and JSP container


will call jspInit() method and _jspService() methods.

The _jspService() method will create the output that will be sent by
JSP container to client browser.
40. How will you implement Auto
Refresh of page in JSP?
We can use setIntHeader() method to set the refresh frequency with
which we want to auto-refresh a JSP page.

We can send key “Refresh” with the time in seconds for auto refresh
of the JSP page.

E.g. response.setIntHeader(“Refresh”,10)
41. What are the important status
codes in HTTP?
Every HTTP request comes back with a status code from the server.
The important status codes in HTTP are as follows:

1. 200: It means the request is successful.


2. 400: It means the request was bad.
3. 401: It means request was not authorized.
4. 404: It means the resource requested was not found.
5. 503: It means the service is not available.
42. What is the meaning of Accept
attribute in HTTP header?
In HTTP header, Accept attribute is used to specify the MIME types
that a HTTP client or browser can handle. MIME type is the
identifier for specifying the type of file/data that we are planning to
pass over the internet.
43. What is the difference between
Expression and Scriptlet in JSP?
We use Expression in a JSP to return a value and display it at a
specific location. It is generally used for dynamically print
information like- time, counter etc in a HTML code.

Scriptlet is for writing Java code in a JSP. We can define variable,


methods etc in a Scriptlet. A Scriptlet can handle much more
complex code and can be also reused.
44. How will you delete a Cookie in
JSP?
We can use following options to delete a Cookie in JSP:

1. setMaxAge(): we can set the maximum age of a cookie.


After this time period, Cookie will expire and will be
deleted.

2. Header: We can also set the expiry time in header of


response. Respone.setHeader(). This will also expire the
cookie after specified time period.
45. How will you use a Cookie in JSP?

We can use a Cookie in JSP by performing following steps:

First we create a Cookie object. We set the name and value of the
cookie to be created.

We set the expiry time of the Cookie by setting the maximum age.
We can use setMaxAge() method for this.

Finally, we can send the cookie in a HTTP Response by sending it


in HTTP header. In this way cookie goes to client browser and gets
stored there till the maximum age is not achieved.

Once a Cookie is set in the client browser, we can call getCookies()


method to get the list of all the cookies set in Client. We iterate
through the list of all the cookies and get the value of the cookie that
was set in earlier request.

In this way we can use Cookie to set some information at client side
and retrieve its value.
46. What is the main difference
between a Session and Cookie in JSP?
A Session is always stored at the Server side. In JSP, session is a
built-in object in JSP container.

A Cookie is always stored at the client side.

We can use both the methods for Session tracking. But Cookie
method needs permission from user for storing cookie at the client
location.
47. How will you prevent creation of
session in JSP?
We can simply set the session attribute as false in page directive to
prevent creation of session object.

E.g. <% @page session=”false” %>


48. What is an output comment in
JSP?
We can write output in JSP in such a way that it becomes a comment
in HTML code. This comment will not be visible in the web
browser. But when we view page source to see HTML, we can see
output comment.

An HTML comment is of following format:

<!-- comment -->

If we output comment in above format, it will be visible to client.


49. How will you prevent caching of
HTML output by web browser in
JSP?
We can use set the header in response object for Cache-Control to
specify no caching.

Sample code is as follows:

response.setHeader(“Cache-Control”, “no-store”);
response.setDateHeader(“Expires”,”0”);
50. How will you redirect request to
another page in browser in JSP code?
We can use sendRedirect() method in JSP to redirect the request to
another location or page.

In this case the request will not come back to server. It will redirect
in the browser itself.

Sample code is as follows:

<% response.sendRedirect(URL); %>


51. What is the difference between
sendRedirect and forward in a JSP?
Both forward and sendRedirect are mechanisms of sending a client
to another page. The main difference between these two are as
follows:

1. In forward, the processing takes place at server side. In


case of sendRedirect() the processing takes place the
client side.

2. In forward, the request is transferred to another resource


within same server. In case of sendRedirect the request can
be transferred to resource on some other server.

3. In forward only one request call is consumed. In case of


sendRedirect two request response calls are created and
consumed.

4. The forward is declared in RequestDispatcher interface.


Where as sendRedirect is declared in
HttpServletResponse object.
52. What is the use of config implicit
object in JSP?
In JSP, config object is of type ServletConfig. This object is created
by Servlet Container for each JSP page. It is used for setting
initialization parameters for a specific JSP page.
53. What is the difference between
init-param and context-param?
We can specify both init-param and context-param in web.xml file.

We use init-param to specify the parameters that are specific to a


servlet or jsp. This information is confined to the scope of that JSP.

We use context-param to specify the parameters for overall


application scope. This information does not change easily. It can
be used by all the JSP/Servlet in that Container.
54. What is the purpose of
RequestDispatcher?
We use RequestDispatcher interface to forward requests to other
resources like HTML, JSP etc.

It can also be used to include the content of another page in a JSP.

It has two methods: forward and include.

We have to first get the RequestDispatcher object from the container


and then we can call include or forward method on this object.
55. How can be read data from a
Form in a JSP?
There is a built-in request object in a JSP that provides methods to
read Form data. Some of the methods are as follows::

1. getParameterNames(): This method returns the list of all


the parameters in the Form.

2. getParameter(): We call this method to get the value of


parameter set in the Form. It returns null if the parameter is
not found.

3. getParameterValues(): If a Parameter is mentioned


multiple times in a Form, we use
request.getParameterValues() method to get all the values.
This method returns an array of String values.

4. getParameterMap(): This method returns the map of all


the Parameters in Form.
56. What is a filter in JSP?

We can define filters in JSP to intercept requests from a client or to


change response from a server.

Filter is a Java class that is defined in the deployment descriptor of


web.xml of an application. The JSP container reads filter from
web.xml and applies a filter as per the URL pattern associated with
the filter.

JSP Engine loads all the filters in when we start the server.
57. How can you upload a large file in
JSP?
To upload a file by JSP we can use <input type=”file”> in the Form
data being passed from HTML.

If the file is very large in size, we can set enctype=multipart/form-


data.

We have to use POST method in the Form to send a file.

Once the request is received, we can implement the logic to read


mulitpart data in doPost() method of JSP. There are methods in JSP
framework to read large files via this method.
58. In which scenario, Container
initializes multiple JSP/Servlet
objects?
To initialize multiple JSP objects, we have to specify same Servlet
object multiple times in web.xml.

This indicates to JSP container to initialize separate JSP/Servlet


object for each element. Each of the Servlet instance will have its
own ServletConfig object and parameters.
Java Design Patterns
59. When will you use Strategy Design
Pattern in Java?
Strategy pattern is very useful for implementing a family of
algorithms. It is a behavioral design pattern.

With Strategy pattern we can select the algorithm at runtime. We can


use it to select the sorting strategy for data. We can use it to save
files in different formats like- .txt, .csv, .jpg etc.

In Strategy pattern we create an abstraction, which is an interface


through which clients interact with our system. Behind the
abstraction we create multiple implementation of same interface
with different algorithms.

For a client, at runtime we can vary the algorithm based on the type
of request we have received.

So we use Strategy pattern to hide the algorithm implementation


details from client.

In Java Collections.sort() method uses strategy design pattern.


60. What is Observer design pattern?
In Observer design pattern, there is a Subject that maintains the list
of Observers that are waiting for any update on the Subject. Once
there is an update in Subject it notifies all the observers for the
change.

E.g. In real life, students are waiting for the result of their test. Here
students are the observers and test is the subject. Once the result of
test is known, testing organization notifies all the students about
their result.

The most popular use of Observer pattern is in Model View


Controller (MVC) architectural pattern.

Main issue with Observer pattern is that it can cause memory leaks.
The subject holds a strong reference to observers. If observers are
not de-registered in time, it can lead to memory leak.
61. What are the examples of
Observer design pattern in JDK?
In JDK there are many places where Observer design pattern is
used. Some of these are as follows:

1. java.util.Observer, java.util.Observable

2. javax.servlet.http.HttpSessionAttributeListener

3. javax.servlet.http.HttpSessionBindingListener

4. All implementations of java.util.EventListener, and also in


Swing packages

5. javax.faces.event.PhaseListener
62. How Strategy design pattern is
different from State design pattern in
Java?
State design pattern is a behavioral design pattern that is use for
defining the state machine for an object. Each state of an object is
defined in a child class of State class. When different actions are
taken on an Object, it can change its state.

Strategy pattern is also a behavioral pattern, but it is mainly used


for defining multiple algorithms. With same action of a client, the
algorithm to be used can change.

Some people consider State pattern similar to Strategy pattern,


since an Object changes its Strategy with different method
invocations. But the main difference is that in State pattern internal
state of an Object is one of the determining factors for selecting the
Strategy for change of state.

Where as in Strategy pattern, client can pass some external


parameter in input during method invocation that determines the
strategy to be used at run time.

Therefore State pattern is based on the Object’s internal state,


where as Strategy pattern is based on Client’s invocation.

State pattern is very useful in increasing the maintainability of the


code in a large code-base.
63. Can you explain Decorator design
pattern with an example in Java?
Some people call Decorator pattern as Wrapper pattern as well. It
is used to add the behavior to an object, without changing the
behavior of other objects of same class.

One of the very good uses of Decorator pattern is in java.io


package. We can have a FileInputStream to handle a File. To add
Buffering behavior we can decorate FileInputStream with
BufferedInputStream. To add the gzip behavior BufferedInputStream
we can decorate it with GzipInputStream. To add serialization
behavior to GzipInputStream, we can decorate it with
ObjectInputStream.

E.g.
Open a FileInputStream:

FileInputStream fis = new FileInputStream("/myfile.gz");

Add buffering:

BufferedInputStream bis = new BufferedInputStream(fis);

Add Gzip:

GzipInputStream gis = new GzipInputStream(bis);

Add Serialization:

ObjectInputStream ois = new ObjectInputStream(gis);

So with each step we have decorated the FileInputStream with


additional behavior.
64. What is a good scenario for using
Composite design Pattern in Java?
Some of the good scenarios where Composite design pattern can be
used are as follows:

Tree Structure: The most common use of Composite design pattern


is Tree structure. If you want to represent data in a Tree data
structure, Composite pattern can be used.

E.g. In an Organization, to a Manager has Employees. But Manager


is also an Employee. If we start from CEO level, there is one big
tree for the whole organization structure. Under that big tree there
are many sub-trees. This can be easily represented with Composite
design pattern.

Recursion: Another use of Composite design pattern is Recursion. If


we have a Recursion based algorithm, we need data to be passed to
algorithm in a data structure that treats individual objects and
compositions at each level of recursion uniformly.
E.g. To implement a recursive Polynomial Solving algorithm, we
can use Composite design pattern to store the intermediate results.

Graphics: Another good use of Composite design pattern is in


Graphics. We can group shapes inside a composite and make
higher-level groups of smaller groups of shapes to complete the
graphics to be displayed on screen.
65. Have you used Singleton design
pattern in your Java project?
Yes. Singleton is one of the most popular design patterns in
enterprise level Java applications. Almost in every project we see
some implementation of Singleton.

With Singleton pattern we can be sure that there is only one instance
of a class at any time in the application.

This helps in storing properties that have to be used in the


application in a unique location.
66. What are the main uses of
Singleton design pattern in Java
project?
Some of the main uses of Singleton design pattern in Java are as
follows:

1. Runtime: In JDK, java.lang.Runtime is a singleton-based class. There


is only one instance of Runtime in an application. This is the only
class that interfaces with the environment/machine in which Java
process is running.

2. Enum: In Java, enum construct is also based on Singleton pattern.


Enum values can be accessed globally in same way by all classes.

3. Properties: In an application it makes sense to keep only one copy of


the properties that all classes can access. This can be achieved by
making properties class Singleton so that every class gets same copy
of properties.

4. Spring: In Spring framework, all the beans are by default Singleton


per container. So there is only one instance of bean in a Spring IoC
container. But Spring also provides options to make the scope of a
bean prototype in a container.
67. Why java.lang.Runtime is a
Singleton in Java?
In Java, java.lang.Runtime is implemented on Singleton design
pattern.

Runtime is the class that acts as an interface with the environment in


which Java process is running. Runtime contains methods that can
interact with the environment.

Like- totalmemory() method gives the total memory in JVM.


maxMemory() method gives the maximum memory that JVM can
use.

There is an exit() method to exit the Java process. We do not want


multiple objects in JVM to have exit() method.

Similarly there is gc() method that can run the Garbage Collector.
With only one copy of gc() method, we can ensure that no other
object can run the Garbage Collector when one instance of GC is
already running.

Due to all these reasons there is only one copy of Runtime in Java.
To ensure single copy of Runtime, it is implemented as a Singleton
in Java.
68. What is the way to implement a
thread-safe Singleton design pattern
in Java?
In Java there are many options to implement a thread-safe Singleton
pattern. Some of these are as follows:

1. Double Checked Locking: This is the most popular method


to implement Singleton in Java. It is based on Lazy
Initialization. In this we first check the criteria for locking
before acquiring a lock to create an object. In Java we use
it with volatile keyword.

Sample code:

class DoubleCheckSingleton {
private volatile HelloSingleton helloSingleton; // Use Volatile

public HelloSingleton getHelloSingleton() {


HelloSingleton result = helloSingleton;
if (result == null) {
synchronized(this) { // Synchronize for thread safety
result = helloSingleton;
if (result == null) {
result = new HelloSingleton();
helloSingleton = result;
}
}
}
return result;
}

}
2. Bill Pugh Singleton: We can also use the method by Bill
Pugh for implementing Singleton in Java. In this we use an
Inner Static class to create the Singleton instance.

Sample code:

public class SingletonBillPugh {

// Inner class that holds instance


private static class InnerSingleton{
private static final SingletonBillPugh INSTANCE = new
SingletonBillPugh();
}

// Private constructor
private SingletonBillPugh(){}

public static SingletonBillPugh getInstance(){


return InnerSingleton.INSTANCE;
}
}

When first time SingletonBillPugh is loaded in memory,


InnerSingleton is not loaded. Only when getInstance() method is
called, InnerSingleton class is loaded and an Instance is created.

3. Enum: We can also use Java enum to create thread-safe


implementation. Java enum values are accessible globally
so these can be used as a Singleton.

Sample Code:

public enum SingletonEnum {

INSTANCE;
public static void doImplementation(){
…..
}
}
69. What are the examples of
Singleton design pattern in JDK?
In JDK there are many places where Singleton design pattern is
used. Some of these are as follows:

1. java.lang.Runtime.getRuntime(): This method gives


Runtime class that has only one instance in a JVM.

java.lang.System.getSecurityManager(): This method


returns a SecurityManager for the current platform.

java.awt.Desktop.getDesktop()
70. What is Template Method design
pattern in Java?
It is a behavioral design pattern. We can use it to create an outline
for an algorithm or a complex operation. We first create the skeleton
of a program. Then we delegate the steps of the operation to
subclasses. The subclasses can redefine the inner implementation of
each step.

E.g. While designing a Game in Java, we can implement it as an


algorithm with Template Method pattern. Each step in the game can
be deferred to subclasses responsible for handling that step.

Let say we implement Monopoly game in Java. We can create


methods like initializeGame(), makeMove(), endGame() etc. Each
of these methods can be handled in subclasses in an independent
manner.

We can use same algorithm for Chess game with same set of
abstract methods. The subclass for Chess game can provide the
concrete implementation of methods like initializeGame(),
makeMove(), endGame() etc.

Template Method pattern is very useful in providing customizable


class to users. We can create the core class with a high level
implementation. And our users can customize our core class in their
custom subclasses.
71. What are the examples of Template
method design pattern in JDK?
In JDK there are many places where Template method design
pattern is used. Some of these are as follows:

1. In Java Abstract Collection classes like


java.util.AbstractList, java.util.AbstractSet and
java.util.AbstractMap implement a template for their
corresponding Collection.

2. javax.servlet.http.HttpServlet: In the HttpServlet class all


the doGet(), doPost() etc. methods send a HTTP 405
"Method Not Allowed" error to the response. This error
response is like a Template that can be further customized
for each of these methods.

3. In java.io package there are Stream and Writer classes like


java.io.InputStream, java.io.OutputStream, java.io.Reader
and java.io.Writer that provide non-abstract methods.
These methods are implementation of Template method
design pattern.
72. Can you tell some examples of
Factory Method design pattern
implementation in Java?
Factory Method pattern is a creational design pattern. A Factory is
an object that is used to create more objects.

In general, a Factory object has methods that can be used to create a


type of objects. Some people call it Factory Method design pattern
as well.

Some of the examples of Factory Method pattern in JDK are:

Java.lang.Class.forName()
java.net.URLStreamHandlerFactory.createURLStreamHandler(String)
java.util.Calendar.getInstance()
java.util.ResourceBundle.getBundle()
java.text.NumberFormat.getInstance()
java.nio.charset.Charset.forName()
java.util.EnumSet.of()
javax.xml.bind.JAXBContext.createMarshaller()
73. What is the benefit we get by
using static factory method to create
object?
By using Static Factory Method we encapsulate the creation process
of an object. We can use new() to create an Object from its
constructor. Instead we use static method of a Factory to create the
object. One main advantage of using Factory is that Factory can
choose the correct implementation at runtime and create the right
object. The caller of method can specify the desired behavior.

E.g. If we have a ShapeFactory with createShape(String type)


method. Client can call ShapeFactory.createShape(“Circle”) to get
a circular shape. ShapeFactory.createShape(“Square”) will return
square shape. In this way, ShapeFactory knows how to create
different shapes based on the input by caller.

Another use of Factory is in providing access to limited resources


to a large set of users.

E.g. In ConnectionPool, we can limit the total number of


connections that can be created as well as we can hide the
implementation details of creating connection. Here ConnectionPool
is the factory. Clients call static method
ConnectionPool.getConnection().
74. What are the examples of Builder
design pattern in JDK?
In JDK there are many places where Builder design pattern is used.
Some of these are as follows:

1. java.lang.StringBuilder.append(): StringBuilder is based


on Builder pattern.

2. java.nio.IntBuffer.put(): Invocation of put() method return


IntBuffer. Also there are many variants of this method to
build the IntBuffer.

3. javax.swing.GroupLayout.Group.addComponent(): We can
use addComponent() method to build a UI that can contain
multiple levels of components.

4. java.lang.Appendable

5. java.lang.StringBuffer.append(): StringBuffer is similar to


StringBuilder and it is also based on Builder design
pattern.
75. What are the examples of
Abstract Factory design pattern in
JDK?
In JDK there are many places where Abstract Factory design pattern
is used. Some of these are as follows:

javax.xml.xpath.XPathFactory.newInstance()

javax.xml.parsers.DocumentBuilderFactory.newInstance()

javax.xml.transform.TransformerFactory.newInstance()
76. What are the examples of
Decorator design pattern in JDK?
In JDK there are many places where Decorator design pattern is
used. Some of these are as follows:

1. In java.io package many classes use Decorator pattern.


Subclasses of java.io.InputStream, OutputStream, Reader
and Writer have a constructor that can take the instance of
same type and decorate it with additional behavior.

2. In java.util.Collections, there are methods like


checkedCollection(), checkedList(), checkedMap(),
synchronizedList(), synchronizedMap(),
synchronizedSet(), unmodifiableSet(), unmodifiableMap()
and unmodifiableList() methods that can decorate an object
and return the same type.

3. In javax.servlet package, there are classes like


javax.servlet.http.HttpServletRequestWrapper and
HttpServletResponseWrapper that are based on Decorator
design pattern.
77. What are the examples of Proxy
design pattern in JDK?
Proxy design pattern provides an extra level of indirection for
providing access to another object. It can also protect a real object
from any extra level of complexity.

In JDK there are many places where Proxy design pattern is used.
Some of these are as follows:

java.lang.reflect.Proxy

java.rmi.*

javax.inject.Inject

javax.ejb.EJB

javax.persistence.PersistenceContext
78. What are the examples of Chain of
Responsibility design pattern in JDK?
In JDK there are many places where Chain of Responsibility design
pattern is used. Some of these are as follows:

1. java.util.logging.Logger.log(): In this case Logger class


provides multiple variations of log() method that can take
the responsibility of logging from client in different
scenarios. The client has to just call the appropriate log()
method and Logger will take care of these commands.

2. javax.servlet.Filter.doFilter(): In the Filter class, the


Container calls the doFilter method when a
request/response pair is passed through the chain. With
filter the request reaches to the appropriate resource at the
end of the chain. We can pass FilterChain in doFilter()
method to allow the Filter to pass on the request and
response to the next level in the chain.
79. What are the main uses of
Command design pattern?
Command design pattern is a behavioral design pattern. We use it to
encapsulate all the information required to trigger an event. Some of
the main uses of Command pattern are:

1. Graphic User Interface (GUI): In GUI and menu items, we


use command pattern. By clicking a button we can read the
current information of GUI and take an action.

2. Macro Recording: If each of user action is implemented as


a separate Command, we can record all the user actions in
a Macro as a series of Commands. We can use this series
to implement the “Playback” feature. In this way, Macro
can keep on doing same set of actions with each replay.

3. Multi-step Undo: When each step is recorded as a


Command, we can use it to implement Undo feature in
which each step can by undo. It is used in text editors like
MS-Word.

4. Networking: We can also send a complete Command over


the network to a remote machine where all the actions
encapsulated within a Command are executed.

5. Progress Bar: We can implement an installation routine as


a series of Commands. Each Command provides the
estimate time. When we execute the installation routine,
with each command we can display the progress bar.

6. Wizard: In a wizard flow we can implement steps as


Commands. Each step may have complex task that is just
implemented within one command.
7. Transactions: In a transactional behavior code there are
multiple tasks/updates. When all the tasks are done then
only transaction is committed. Else we have to rollback the
transaction. In such a scenario each step is implemented as
separate Command.
80. What are the examples of
Command design pattern in JDK?
In JDK there are many places where Command design pattern is
used. Some of these are as follows:

All implementations of java.lang.Runnable

All implementations of javax.swing.Action


81. What are the examples of
Interpreter design pattern in JDK?
Interpreter design pattern is used to evaluate sentences in a
language. E.g. In SQL we can use it to evaluate a query by
evaluating each keyword like SELECT, FROM, WHERE clause.

In an Interpreter implementation there is a class for each


keyword/symbol. A sentence is just a composite of these keywords.
But the sentence is represented by Syntax tree that can be
interpreted.

In JDK there are many places where Interpreter design pattern is


used. Some of these are as follows:

java.util.Pattern

java.text.Normalizer

Subclasses of java.text.Format: DateFormat,


MessageFormat, NumberFormat

Subclasses of javax.el.ELResolver: ArrayELResolver,


MapELResolver, CompositeELResolver etc.
82. What are the examples of
Mediator design pattern in JDK?
By using Mediator pattern we can decouple the multiple objects that
interact with each other. With a Mediator object we can create
many-to-many relationships in multiple objects.

In JDK there are many places where Mediator design pattern is


used. Some of these are as follows:

java.util.Timer: schedule() methods in Timer class act as


Mediator between the clients and the TimerTask to be
scheduled.

java.util.concurrent.Executor.execute(): The execute()


method in an Executor class acts as a Mediator to execute
the different tasks.

java.util.concurrent.ExecutorService

java.lang.reflect.Method.invoke(): In Method class of


reflection package, invoke() method acts as a Mediator.

java.util.concurrent.ScheduledExecutorService: Here also


schedule() method and its variants are Mediator pattern
implementations.
83. What are the examples of Strategy
design pattern in JDK?
In JDK there are many places where Strategy design pattern is used.
Some of these are as follows:

1. java.util.Comparator: In a Comparator we can use


compare() method to change the strategy used by
Collections.sort() method.

2. javax.servlet.http.HttpServlet: In a HttpServlet class


service() and doGet(), doPost() etc. methods take
HttpServletRequest and HttpServletResponse and the
implementor of Servlet processes it based on the strategy it
selects.
84. What are the examples of Visitor
design pattern in JDK?
By using Visitor design pattern we can add new virtual methods to
existing classes without modifying their core structure.

In JDK there are many places where Visitor design pattern is used.
Some of these are as follows:

javax.lang.model.element.AnnotationValue and
AnnotationValueVisitor

java.nio.file.FileVisitor and SimpleFileVisitor

javax.lang.model.type.TypeMirror and TypeVisitor

javax.lang.model.element.Element and ElementVisitor

javax.faces.component.visit.VisitContext and
VisitCallback
85. How Decorator design pattern is
different from Proxy pattern?
Main differences between Decorator and Proxy design pattern are:

Decorator provides an enhanced interface after decorating


it with additional features. Proxy provides same interface
since it is just acting as a proxy to another object.

Decorator is a type of Composite pattern with only one


component. But each decorator can add additional
features. Since it is one component in Decorator, there is
no object aggregation.

Proxy can also provide performance improvement by lazy


loading. There is nothing like this available in Decorator.

Decorator follows recursive composition. Proxy is just


one object to another object access.

Decorator is mostly used for building a variety of objects.


Proxy is mainly used for access to another object.
86. What are the different scenarios
to use Setter and Constructor based
injection in Dependency Injection
(DI) design pattern?
We use Setter injection to provide optional dependencies of an
object. Constructor injection is used to provide mandatory
dependency of an object.

In Spring IoC, Dependency Injection is heavily used. There we have


to differentiate between the scenario suitable for Setter based and
Constructor based dependency injection.
87. What are the different scenarios
for using Proxy design pattern?
Proxy design pattern can be used in a wide variety of scenario in
Java. Some of these are as follows:

1. Virtual Proxy: This is a virtual object that acts as a proxy


for objects that are very expensive to create. It is used in
Lazy Loading. When client makes the first request, the real
object is created.

2. Remote Proxy: This is a local object that provides access


to a remote object. It is generally used in Remote Method
Invocation (RMI) and Remote Procedure Call (RPC). It is
also known as a Stub.

3. Protective Proxy: This is an object that control the access


to a Master object. It can authenticate and authorize the
client for accessing the Master object. If client has right
permissions, it allows client to access the main object.

4. Smart Proxy: It is an object that can add additional


information to the main object. It can track the number of
other objects accessing the main object. It can track the
different clients from where request is coming. It can even
deny access to an object if the number of requests is
greater than a threshold.
88. What is the main difference
between Adapter and Proxy design
pattern?
Adapter pattern provides a different interface to an object. But the
Proxy always provides same interface to the object.

Adapter is like providing an interface suitable to client’s use. But


Proxy is same interface that has additional feature or check.

E.g. In electrical appliances we use Adapter to convert from one


type of socket to another type of socket. In case of proxy, we have a
plug with built-in surge protector. The interface for plug and the
original device remains same.
89. When will you use Adapter design
pattern in Java?
If we have two classes with incompatible interfaces, we use
Adapter pattern to make it work. We create an Adapter object that
can adapt the interface of one class to another class.

It is generally used for working with third party libraries. We create


an Adapter class between third party code and our class. In case of
any change in third party code we have to just change the Adapter
code. Rest of our code can remain same and just take to Adapter.
90. What are the examples of Adapter
design pattern in JDK?
In JDK there are many places where Adapter design pattern is used.
Some of these are as follows:

java.util.Arrays.asList(): This method can adapt an Array


to work as a List.

java.util.Collections.list(): This method can adapt any


collection to provide List behavior.

java.util.Collections.enumeration(): This method returns


an enumeration over the collection.

java.io.InputStreamReader(InputStream): This method


adapts a Stream to Reader class.

java.io.OutputStreamWriter(OutputStream): This method


adapts an OutputStream to Writer class.

javax.xml.bind.annotation.adapters.XmlAdapter.marshal()
91. What is the difference between
Factory and Abstract Factory design
pattern?
With Factory design pattern we can create concrete products of a
type that Factory can manufacture. E.g. If it is CarFactory, we can
produce, Ford, Toyota, Honda, Maserati etc.

With Abstract Factory design pattern we create a concrete


implementation of a Factory. E.g. DeviceFactory can be Abstract
and it can give us GoogleDeviceFactory, AppleDeviceFactory etc.
With AppleDeviceFactory we will get products like- iPhone, iPad,
Mac etc. With GoogleDeviceFactory we will get products like-
Nexus phone, Google Nexus tablet, Google ChromeBook etc.

So it is a subtle difference between Factory and Abstract Factory


design pattern. One way to remember is that within Abstract Factory
pattern, Factory pattern is already implemented.
92. What is Open/closed design
principle in Software engineering?
Open/closed design principle states “software entities (classes,
modules, functions, etc.) should be open for extension, but closed
for modification”.

Open/closed principle term was originated by Bertrand Meyer in


his book Object Oriented Software Construction.

As per this principle, if a module is available for extension then it


is considered open. If a module is available for use by other
modules then it is considered closed.

Further Robert C. Martin has mentioned it as O in SOLID principles


of Object Oriented design.

It is used in State and Strategy design patterns. Context class is


closed for modification. But new functionality can be added by
writing new strategy code.
93. What is SOLID design principle?
SOLID word in SOLID design principle is an acronym for:

1. S: Single responsibility. A Class should have a single


responsibility.
2. O: Open-closed. Software entities should be open for
extension but closed for modification.
3. L: Liskov substitution. Objects in a program should be
replaceable by subclasses of same type without any
adverse impact.
4. I: Interface segregation. Multiple client specific interfaces
are preferable over single generic interface.
5. D: Dependency inversion. Program should depend on
abstract entities. It should not depend on concrete
implementation of an interface.

This principle was mentioned by Robert C. Martin. These are


considered five basic principles of Object Oriented design.

If we follow these principles, then we can create a stable program


that is easy to maintain and can be extended over time.
94. What is Builder design pattern?
Builder design pattern is a creational design pattern. We can use
Builder pattern to create complex objects with multiple options.

E.g. when we have to create a Meal in a restaurant we can use


Builder pattern. We can keep adding options like- Starter, Drink,
Main Course, and Dessert etc. to create complete meal. When a user
selects other options of Starter, Drink Main Course, Dessert another
type of meal is created.

Main feature of Builder pattern is step-by-step building of a


complex object with multiple options.
95. What are the different categories
of Design Patterns used in Object
Oriented Design?
In Object Oriented design mainly three categories of design patterns
are used. These categories are:

Creational Design Patterns:


Builder
Factory Method
Abstract Factory
Object Pool
Singleton
Prototype

Structural Design Patterns:


Adapter
Bridge
Façade
Decorator
Composite
Flyweight
Proxy

Behavioral Design Patterns:


Command
Iterator
Chain of Responsibility
Observer
State
Strategy
Mediator
Interpreter
96. What is the design pattern
suitable to access elements of a
Collection?
We can use Iterator design pattern to access the individual elements
of a Collection. In case of an ordered collection we can get Iterator
that returns the elements in an order.

In Java there are many implementation of Iterator in Collections


package. We have iterators like- Spliterator, ListIterator etc. that
implement Iterator pattern.
97. How can we implement Producer
Consumer design pattern in Java?
We can use BlockingQueue in Java to implement Producer
Consumer design pattern.

It is a concurrent design pattern.


98. What design pattern is suitable to
add new features to an existing
object?
We can use Decorator design pattern to add new features to an
existing object. With a Decorator we work on same object and
return the same object with more features. But the structure of the
object remains same since all the decorated versions of object
implement same interface.
99. Which design pattern can be used
when to decouple abstraction from the
implementation?
We can use Bridge design pattern to detach the implementation from
the abstraction.

Bridge is mainly used for separation of concern in design. We can


create an implementation and store it in the interface, which is an
abstraction. Where as specific implementation of other features can
be done in concrete classes that implement the interface.

Often Bridge design pattern is implemented by using Adapter


pattern.

E.g. we have Shape interface. We want to make Square and Circle


shapes. But further we want to make RedSquare, BlackSquare
shapes and GreenCircle, WhiteCircle shapes. In this case rather
than creating one hierarchy of all the shapes, we separate the Color
concern from Shape hierarchy.

So we create two hierarchies. One is Shape to Square and Shape to


Circle hierarchy. Another one is Color to Red, Black, Green, White
hierarchy. In this way we can create multiple types of shapes with
multiple colors with Bridge design pattern.
100. Which is the design pattern used
in Android applications?
Android applications predominantly use Model View Presenter
design pattern.

1. Model: This is the domain model of the Android


application. It contains the business logic and business
rules.

2. View: These are the UI components in your application.


These are part of the view. Also any events on UI
components are part of view module.

3. Presenter: This is the bridge between Model and View to


control the communication. Presenter can query the model
and return data to view to update it.

4. E.g. If we have a Model with large news article data, and


view needs only headline, then presenter can query the
data from model and only give headline to view. In this
way view remains very light in this design pattern.
101. How can we prevent users from
creating more than one instance of
singleton object by using clone()
method?
First we should not implement the Cloneable interface by the object
that is a Singleton.

Second, if we have to implement Cloneable interface then we can


throw exception in clone() method.

This will ensure that no one can use clone() method or Cloneable
interface to create more than one instance of Singleton object.
102. What is the use of Interceptor
design pattern?
Interceptor design pattern is used for intercepting a request. Primary
use of this pattern is in Security policy implementation.

We can use this pattern to intercept the requests by a client to a


resource. At the interception we can check for authentication and
authorization of client for the resource being accessed.

In Java it is used in javax.servlet.Filter interface.

This pattern is also used in Spring framework in HandlerInterceptor


and MVC interceptor.
103. What are the Architectural
patterns that you have used?
Architectural patterns are used to define the architecture of a
Software system. Some of the patterns are as follows:

1. MVC: Model View Controller. This pattern is extensively


used in the architecture of Spring framework.

2. Publish-subscribe: This pattern is the basis of messaging


architecture. In this case messages are published to a
Topic. And subscribers subscribe to the topic of their
interests. Once the message is published to a topic in
which a Subscriber has an interest, the message is
consumed by the relevant subscriber.

3. Service Locator: This design pattern is used in a service


like JNDI to locate the available services. It uses as
central registry to maintain the list of services.

4. n-Tier: This is a generic design pattern to divide the


architecture in multiple tiers. E.g. there is 3-tier
architecture with Presentation layer, Application layer and
Data access layer. It is also called multi-layer design
pattern.

5. Data Access Object (DAO): This pattern is used in


providing access to database objects. The underlying
principle is that we can change the underlying database
system, without changing the business logic. Since
business logic talks to DAO object, there is no impact of
changing Database system on business logic.

6. Inversion of Control (IoC): This is the core of Dependency


Injection in Spring framework. We use this design pattern
to increase the modularity of an application. We keep the
objects loosely coupled with Dependency Injection.
104. What are the popular uses of
Façade design pattern?
Some of the popular uses of Façade design pattern are as follows:

1. A Façade provides convenient methods for common tasks


that are used more often.
2. A Façade can make the software library more readable.
3. A Façade can reduce the external dependencies on the
working of inner code.
4. A Façade can act as a single well-designed API by
wrapping a collection of poorly designed APIs.
5. A Façade pattern can be used when a System is very
complex and difficult to use. It can simplify the usage of
complex system.
105. What is the difference between
Builder design pattern and Factory
design pattern?
Both Factory and Builder patterns are creational design patterns.
They are similar in nature but Factory pattern is a simplified generic
version of Builder pattern.

We use Factory pattern to create different concrete subtypes of an


Object. The client of a Factory may not know the exact subtype. E.g.
If we call createDrink() of a Factory, we may get Tea or Coffee
drinks.

We can also use Builder pattern to create different concrete


subtypes of an object. But in the Builder pattern the composition of
the object can be more complex. E.g. If we call createDrink() for
Builder, we can getCappuccino Coffee with Vanilla Cream and
Sugar, or we can get Latte Coffee with Splenda and milk cream.

So a Builder can support creation of a large number of variants of


an object. But a Factory can create a broader range of known
subtypes of an object.
106. What is Memento design
pattern?
Memento design pattern is used to implement rollback
feature in an object. In a Memento pattern there are three
objects:

Originator: This is the object that has an internal state.

Caretaker: This is the object that can change the state of


Originator. But it wants to have control over rolling back
the change.

Memento: This is the object that Caretaker gets from


Originator, before making and change. If Caretaker wants
to Rollback the change it gives Memento back to
Originator. Originator can use Memento to restore its own
state to the original state.

E.g. One good use of memento is in online Forms. If we


want to show to user a form pre-populated with some
data, we keep this copy in memento. Now user can
update the form. But at any time when user wants to reset
the form, we use memento to make the form in its original
pre-populated state. If user wants to just save the form
we save the form and update the memento. Now onwards
any new changes to the form can be rolled back to the
last saved Memento object.
107. What is an AntiPattern?
An AntiPattern is opposite of a Design Pattern. It is a common
practice in an organization that is used to deal with a recurring
problem but it has more bad consequences than good ones.

AntiPattern can be found in an Organization, Architecture or


Software Engineering.

Some of the AntiPatterns in Software Engineering are:

1. Gold Plating: Keep on adding extra things on a working


solution even though these extra things do not add any
additional value.

2. Spaghetti Code: Program that are written in a very


complex way and are hard to understand due to misuse of
data structures.

3. Coding By Exception: Adding new code just to handle


exception cases and corner case scenarios.

4. Copy Paste Programming: Just copying the same code


multiple times rather than writing generic code that can be
parameterized.
108. What is a Data Access Object
(DAO) design pattern?
DAO design pattern is used in the data persistent layer of a Java
application. It mainly uses OOPS principle of Encapsulation.

By using DAO pattern it makes the application loosely coupled and


less dependent on actual database.

We can even implement some in-memory database like H2 with


DAO to handle the unit-testing.

In short, DAO hides the underlying database implementation from


the class that accesses the data via DAO object.

Recently we can combine DAO with Spring framework to inject any


DB implementation.
Spring
109. What is Spring framework?
Spring is development framework for Java programming. It is an
open source development framework for Enterprise Java.

The core features of Spring Framework can be used in developing a


Java Enterprise application.

It has many extensions and jars for developing web applications on


top of Java EE platform.

With Spring we can develop large-scale complex Java applications


very easily. It is also based on good design patterns like
Dependency Injection, Aspect oriented programming for developing
extensible feature rich software.
110. What are the benefits of Spring
framework in software development?
Many benefits of Spring framework are:

Lightweight Framework: Basic Spring framework is very small in


size. It is easy to use and does not add a lot of overhead on
software. It just has 2 MB in basic version.

Container: Spring framework provides the basic container that


creates and manages the life cycle of application objects like Plain
old Java objects (POJO). It also stores the configuration files of
application objects to be created.

Dependency Injection (DI): Spring provided loose coupling is


application by Dependency Injection. It uses Inversion of Control
technique by which objects specify their dependencies to Spring
container instead of creating new objects themselves.

Aspect Oriented Programming (AOP): Spring framework promotes


and provides support for Aspect oriented programming in Java.
This helps in separating application business logic from system
services that are common across all the business logic. E.g. Logging
can be a cross cutting concern in an Application.

Transaction Management: Spring provides a framework for


transaction management. So a developer does not have to implement
it from scratch. Spring Transaction Management is so powerful that
we can scale it from one local transaction to global transactions in a
cluster.

MVC Framework: For Web applications, Spring provides MVC


framework. This framework is based on MVC design pattern and
has better features compared to other web frameworks.

Exception Handling: Spring also gives support for a common API to


handle exceptions in various technologies like- Hibernate, JDBC
etc.
111. What are the modules in Core
Container of Spring framework?
Spring framework has a Core Container. Modules in Core Container
are:

Core module
Bean module
Context module
Spring Expression Language module
112. What are the modules in Data
Access/Integration layer of Spring
framework?
Modules in Data Access/Integration Layer of Spring framework are:

JDBC module: An abstraction layer to remove tedious JDBC


coding.
ORM module Integration layers for Object Relational Mapping
OXM module: An abstraction layer to support Object XML
mapping.
Java Messaging Service (JMS) module: Module for producing and
consuming messages.
Transactions module: Transaction Management for POJO classes
113. What are the modules in Web
layer of Spring framework?
Modules in Web Layer of Spring framework are:

Web module: This provides basic web-oriented integration features.


Servlet module: Support for Servlet Listeners.
WebSocket module: Support for Web Socket style messaging.
Portlet module: MVC implementation for Portlet environment.
114. What is the main use of Core
Container module in Spring
framework?
As the name suggests, Spring Core Container is the core of Spring
framework. It gives the basic functionality of the Spring. All the
parts of Spring Framework are built on top of Core Container.

Its main use is to provide Dependency Injection (DI) and Inversion


of control (IOC) features.
115. What kind of testing can be done
in Spring Test Module?
Spring Test Module provides support for Unit testing as well as
Integration testing of Spring components. It allows using JUnit or
TestNG testing frameworks. It also gives ability to mock objects to
use the test code.
116. What is the use of BeanFactory in
Spring framework?
BeanFactory is the main class that helps in implementing Inversion
of Control pattern in Spring. It is based on the factory design
pattern. It separates the configuration and dependencies of an
application from the rest of application code.

Implementations of BeanFactory like XmlBeanFactory class are


used by applications built with Spring.
117. Which is the most popular
implementation of BeanFactory in
Spring?
XMLBeanFactory is the most popular implementation of
BeanFactory in Spring.
118. What is XMLBeanFactory in
Spring framework?
XMLBeanFactory is one of the most useful implementation of
BeanFactory in Spring. This factory loads its beans based on the
definitions mentioned in an XML file.

Spring container reads bean configuration metadata from an XML


file and creates a fully configured application with the help of
XMLBeanFactory class.
119. What are the uses of AOP module
in Spring framework?
AOP module is also known as Aspect Oriented Programming
module. Its uses are:

Development of aspects in a Spring based application


Provides interoperability between Spring and other AOP
frameworks
Supports metadata programming to Spring
120. What are the benefits of JDBC
abstraction layer module in Spring
framework?
Spring provides JDBC abstraction layer module. Main benefits of
this module are:

Helps in keeping the database code clean and simple.


Prevents problems that result from a failure to close database
resources.
Provides a layer of useful exceptions on top of the error messages
given by different database servers.
Based on Spring’s AOP module
Provides transaction management services for objects in a Spring
application
121. How does Spring support Object
Relational Mapping (ORM)
integration?
Spring supports Object Relational Mapping (ORM) by providing
ORM Module. This module helps in integrating with popular ORM
framework like Hibernate, JDO, and iBATIS SQL Maps etc.

Transaction Management module of Spring framework supports all


of these ORM frameworks as well as JDBC.
122. How does Web module work in
Spring framework?
Spring provides support for developing web application by using
Web module. This module is built on application context module
that provides context for web-based applications.

This module also supports web-oriented integration features like-


transparently handling multipart requests for uploading files,
programmatically binding request parameters to business objects
etc.

This module also supports integration with popular web


frameworks like Jakarta Struts, JSF, and Tapestry etc.
123. What are the main uses of Spring
MVC module?
Spring-webmvc module is also known as Web-servlet module. It is
based on Web Model View Controller pattern.

Main uses of this module are:

Integration of Spring with other MVC frameworks


Supports IoC to provide clean separation of controller logic from
business objects
Provides clean separation between domain model code and web
forms
Allows developers to declaratively bind request parameters to
business objects
124. What is the purpose of Spring
configuration file?
Spring application can be configured by an XML file. This file
contains information of classes and how these classes are
configured and introduced to each other.

Spring IoC container uses some kind of configuration metadata. This


configuration metadata represents how an application developer
tells the Spring container to instantiate, configure, and assemble the
objects in your application. This configuration metadata is stored in
Spring configuration file.

The other ways of specifying configuration metadata are Java based


configuration and Annotation based configuration.
125. What is the purpose of Spring
IoC container?
The Spring IoC Container is responsible for:

Creating the objects


Configuring the objects
Managing dependency between objects (with dependency injection
(DI))
Wiring the objects together
Managing complete lifecycle of objects
126. What is the main benefit of
Inversion of Control (IOC) principle?
Inversion of Control (IOC) principle is the base of Spring
framework. It supports dependency injection in an application. With
Dependency Injection, a programmer has to write minimal code. It
also makes easier to test an application.

Most important benefit is that it leads to loose coupling within


objects. With loose coupling it is easier to change the application
with new requirements.
127. Does IOC containers support
Eager Instantiation or Lazy loading of
beans?
IOC Container in Spring supports both the approaches. Eager
instantiation as well as lazy loading of beans.
128. What are the benefits of
ApplicationContext in Spring?
ApplicationContext in Spring provides following benefits:

Bean factory methods: These are used to access application


components
Load File Resources: It helps in loading file resources in a generic
fashion
Publish Events: It enables publishing events to registered listeners
Internationalization Support: Ability to resolve messages to support
internationalization
Parent Context: Ability to inherit from a parent context
129. How will you implement
ApplicationContext in Spring
framework?
ApplicationContext in Spring can be implemented in one of the
following three ways:

FileSystemXmlApplicationContext: If we want to load the


definitions of beans from an XML file then
FileSystemXmlApplicationContext is used. The full path of XML
bean configuration file is provided to the constructor.
ClassPathXmlApplicationContext: To loads the definitions of beans
from an XML file in the CLASSPATH, we use
ClassPathXmlApplicationContext. It is used for application context
embedded in jars.

WebXmlApplicationContext: To provide configuration for a web


application WebXmlApplicationContext is used. While the
application is running, it is read only. But it can be reloaded if
underlying application supports it.
130. Explain the difference between
ApplicationContext and BeanFactory
in Spring?
Main differences between ApplicationContext and BeanFactory are:

Automatic BeanPostProcessor registration: BeanFactory does not


support BeanPostProcessor registration. Whereas
ApplicationContext support this.

Automatic BeanFactoryPostProcessor registration: BeanFactory


also does not allow Automatic BeanFactoryPostProcessor
registration. Whereas ApplicationContext allows this.

MessageSource access: BeanFactory is not convenient for


MessageSource access. ApplicationContext is quite convenient for
MessageSource access.

ApplicationEvent: We cannot publish ApplicationEvent with


BeanFactory. But ApplicationContext provides ability to publish
ApplicationEvent.
131. Between ApplicationContext and
BeanFactory which one is preferable
to use in Spring?
Spring documentation recommends using ApplicationContext in
almost all the cases. ApplicationContext has all the functionality of
BeanFactory.
132. What are the main components of
a typical Spring based application?
In a Spring based application, main components are:
Spring configuration XML file: This is used to configure Spring
application
API Interfaces: Definition of API interfaces for functions provided
by application
Implementation: Application code with implementation of APIs
Aspects: Spring Aspects implemented by application
Client: Application at client side that is used for accessing functions
133. Explain Dependency Injection
(DI) concept in Spring framework?
Dependency Injection is a software design pattern. It is used to
implement Inversion of Control (IOC) in Spring framework. As per
this pattern, we do not create objects in an application by calling
new. Rather, we describe how an object should be created. In this
way creation of an object is not tightly coupled with another object.

A container is responsible for creating and wiring the objects. The


container can call injecting code and wire the objects as per the
configuration at runtime.
134. What are the different roles in
Dependency Injection (DI)?
There are four roles in Dependency Injection:

Service object(s) to be used


Client object that depends on the service
Interface that defines how client uses services
Injector responsible for constructing services and injecting them
into client
135. Spring framework provides what
kinds of Dependency Injection
mechanism?
Spring framework provides two types of Dependency Injection
mechanism:

Constructor-based Dependency Injection: Spring container can


invoke a class constructor with a number of arguments. This
represents a dependency on other class.

Setter-based Dependency Injection: Spring container can call setter


method on a bean after creating it with a no-argument constructor or
no-argument static factory method to instantiate another bean.
136. In Spring framework, which
Dependency Injection is better?
Constructor-based DI or Setter-based
DI?
Spring framework provides support for both Constructor-based and
Setter-based Dependency Injection. There are different scenarios in
which these options can be used.

It is recommended to use Constructor-based DI for mandatory


dependencies. Whereas Setter-based DI is used for optional
dependencies.
137. What are the advantages of
Dependency Injection (DI)?
Dependency Injection (DI) pattern has following advantages:

Dependency Injection reduces coupling between a class and its


dependencies.

With Dependency Injection (DI), we can do concurrent or


independent software development. Two teams can work parallel
on classes that will be used by each other.

In Dependency Injection (DI), the client can be configured in


multiple ways. It needs to just work with the given interface. Rest of
the implementation can be changed and configured for different
features.

Dependency injection is also used to export a system's configuration


details into configuration files. So we can configure same
application run in different environments based on configuration.
E.g. Run in Test environment, UAT environment, and Production
environment.

Dependency Injection (DI) applications provide more ease and


flexibility of testing. These can be tested in isolation in Unit Test.

Dependency injection (DI) isolates client from the impact of design


and implementation changes. Therefore, it promotes reusability,
testability and maintainability.
138. What are the disadvantages of
Dependency Injection (DI)?
Dependency Injection (DI) pattern has following disadvantages:

Most of the time Dependency Injection forces developers to use an


injection framework like Spring. This causes dependency on a
framework.

With Dependency Injection, clients are dependent on the


configuration data. This becomes extra task for developers when the
application does not need so many custom configuration values.

Code is difficult to trace and read in Dependency Injection. DI


separates behavior from construction of objects.

Dependency injection increases complexity in the linkages between


classes. It may become harder to manage such complexity outside
the implementation of a class.
139. What is a Spring Bean?
A Spring Bean is a plain old Java object (POJO) that is created and
managed by a Spring container.

There can be more than one bean in a Spring application. But all
these Beans are instantiated and assembled by Spring container.

Developer provides configuration metadata to Spring container for


creating and managing the lifecycle of Spring Bean.

In general a Spring Bean is singleton. Evert bean has an attribute


named "singleton". If its value is true then bean is a singleton. If its
value is false then bean is a prototype bean.

By default the value of this attribute is true. Therefore, by default all


the beans in spring framework are singleton in nature.
140. What does the definition of a
Spring Bean contain?
A Spring Bean definition contains configuration metadata for bean.
This configuration metadata is used by Spring container to:

Create the bean


Manage its lifecycle
Resolve its dependencies
141. What are the different ways to
provide configuration metadata to a
Spring Container?
Spring supports three ways to provide configuration metadata to
Spring Container:

XML based configuration: We can specify configuration data in an


XML file.

Annotation-based configuration: We can use Annotations to specify


configuration. This was introduced in Spring 2.5.

Java-based configuration: This is introduced from Spring 3.0. We


can embed annotations like @Bean, @Import, @Configuration in
Java code to specify configuration metadata.
142. What are the different scopes
of a Bean supported by Spring?
Spring framework support seven types of scopes for a Bean. Out of
these only five scopes are available for a web-aware
ApplicationContext application:

singleton: This is the default scope of a bean. Under this scope,


there is a single object instance of bean per Spring IoC container.

prototype: Under this scope a single bean definition can have


multiple object instances.

request: In this scope, a single bean definition remains tied to the


lifecycle of a single HTTP request. Each HTTP request will have
its own instance of a bean for a single bean definition. It is only
valid in the context of a web-aware Spring ApplicationContext.

session: Under this scope, a single bean definition is tied to the


lifecycle of an HTTP Session. Each HTTP Session will have one
instance of bean. It is also valid in the context of a web-aware
Spring ApplicationContext.

globalSession: This scope, ties a single bean definition to the


lifecycle of a global HTTP Session. It is generally valid in a Portlet
context. It is also valid in the context of a web-aware Spring
ApplicationContext.

application: This scope, limits a single bean definition to the


lifecycle of a ServletContext. It is also valid in the context of a
web-aware Spring ApplicationContext.

websocket: In this scope, a single bean definition is tied to the


lifecycle of a WebSocket. It is also valid in the context of a web-
aware Spring ApplicationContext.
143. How will you define the scope
of a bean in Spring?
In configuration xml, we can specify the scope of bean in its
definition. This is used by container to decide the scope of bean in
Spring.

E.g. <bean id="userService" class="com.um.UserService"


scope="prototype"/>

This is an example of userService bean with prototype scope.


144. Is it safe to assume that a
Singleton bean is thread safe in Spring
Framework?
No, Spring framework does not guarantee anything related to multi-
threaded behavior of a singleton bean. Developer is responsible for
dealing with concurrency issues and maintaining thread safety of a
singleton bean.
145. What are the design-patterns
used in Spring framework?
Spring framework uses many Design patterns. Some of these
patterns are:

Singleton – By default beans defined in spring config files are


singleton. These are based on Singleton pattern.

Template – This pattern is used in many classes like-


JdbcTemplate, RestTemplate, JmsTemplate, JpaTemplate etc.

Dependency Injection – This pattern is the core behind the design of


BeanFactory and ApplicationContext.

Proxy – Aspect Oriented Programming (AOP) heavily uses proxy


design pattern.

Front Controller – DispatcherServlet in Spring is based on Front


Controller pattern to ensure that incoming requests are dispatched to
other controllers.

Factory pattern – To create an instance of an object, BeanFactory is


used. This is based on Factory pattern.

View Helper – Spring has multiple options to separating core code


from presentation in views. Like- Custom JSP tags, Velocity macros
etc.
146. What is the lifecycle of a Bean
in Spring framework?
A Bean in Spring framework goes through following phases in its
lifecycle.

Initialization and creation: Spring container gets the definition of


Bean from XML file and instantiates the Bean. It populates all the
properties of Bean as mentioned in the bean definition.

Setting the Behavior of Bean: In case a Bean implements


BeanNameAware interface, Spring uses setBeanName() method to
pass the bean’s id. In case a Bean implements BeanFactoryAware
interface, Spring uses setBeanFactory() to pass the BeanFactory to
bean.

Post Processing: Spring container uses


postProcesserBeforeInitialization() method to call
BeanPostProcessors associated with the bean. Spring calls
afterPropertySet() method to call the specific initialization methods.
In case there are any BeanPostProcessors of a bean, the
postProcessAfterInitialization() method is called.

Destruction: During the destruction of a bean, if bean implements


DisposableBean, Spring calls destroy() method.
147. What are the two main groups
of methods in a Bean’s lifecycle?
A Bean in Spring has two main groups of lifecycle methods.

Initialization Callbacks: Once all the necessary properties of a Bean


are set by the container, Initialization Callback methods are used for
performing initialization work. A developer can implement method
afterPropertiesSet() for this work.

Destruction Callbacks: When the Container of a Bean is destroyed,


it calls the methods in DisposableBean to do any cleanup work.
There is a method called destroy() that can be used for this purpose
to make Destruction Callbacks.

Recent recommendation from Spring is to not use these methods,


since it can strongly couple your code to Spring code.
148. Can we override main lifecycle
methods of a Bean in Spring?
Yes, Spring framework allows developers to override the lifecycle
methods of a Bean. This is used for writing any custom behavior for
Bean.

You might also like