1000 Java Interview Questions-3
1000 Java Interview Questions-3
Is ++ operation thread-safe in
Java?
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?
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?
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?
By using these methods, you can find out how much of the heap is
used and how much heap space still remains.
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.
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.
When the JVM is started, three types of class loaders are used:
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.
You can also attach meta-data to enum values in Java. Also enum
values are typesafe, where as integer constants are not.
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.
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.
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.
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.
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();
}
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.
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.
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.
E.g.
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?
E.g.
<%@ page attribute="value" %>
E.g.
<%@ taglib uri=“abc.html” prefix=“tag_prefix” >
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:
E.g.
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.
Like- www.abcserver.com?sessionid=1234
36. How do you debug code in JSP?
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.
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:
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.
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.
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.
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.
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.
For a client, at runtime we can vary the algorithm based on the type
of request we have received.
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.
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
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.
E.g.
Open a FileInputStream:
Add buffering:
Add Gzip:
Add Serialization:
With Singleton pattern we can be sure that there is only one instance
of a class at any time in the application.
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:
Sample code:
class DoubleCheckSingleton {
private volatile HelloSingleton helloSingleton; // Use Volatile
}
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:
// Private constructor
private SingletonBillPugh(){}
Sample Code:
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:
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.
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.
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.
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
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:
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:
java.util.Pattern
java.text.Normalizer
java.util.concurrent.ExecutorService
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
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:
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.
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.
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:
There can be more than one bean in a Spring application. But all
these Beans are instantiated and assembled by Spring container.