Sie sind auf Seite 1von 33

JAVA INTERVIEW QUESTIONS AND ANSWERS

1) What is meant by Object Oriented Programming?


OOP is a method of programming in which programs are organised as cooperative
collections of objects. Each object is an instance of a class and each class belong to a
hierarchy.

2) What is a Class?
Class is a template for a set of objects that share a common structure and a common
behavior.

3) What is an Object?
Object is an instance of a class. It has state,behaviour and identity. It is also called as an
instance of a class.

4) What is an Instance?
An instance has state, behavior and identity. The structure and behavior of similar classes
are defined in their common class. An instance is also called as an object.

5) What are the core OOP's concepts?


Abstraction, Encapsulation, Inheritance and Polymorphism are the core OOP's concepts.

6) What is meant by abstraction?


Abstraction defines the essential characteristics of an object that distinguish it from all
other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to
the perspective of the viewer. Its the process of focusing on the essential characteristics of an
object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation?


Encapsulation is the process of compartmentalising the elements of an abtraction that
defines the structure and behaviour. Encapsulation helps to separate the contractual interface
of an abstraction and implementation.

8) What is meant by Inheritance?


Inheritance is a relationship among classes, wherein one class shares the structure or
behaviour defined in another class. This is called Single Inheritance. If a class shares the
structure or behaviour from multiple classes, then it is called Multiple Inheritance.
Inheritance defines "is-a" hierarchy among classes in which one subclass inherits from one or
more generalised superclasses.

9) What is meant by Polymorphism?


Polymorphism literally means taking more than one form. Polymorphism is a characteristic
of being able to assign a different behavior or value in a subclass, to something that was
declared in a parent class.

10) What is an Abstract Class?


Abstract class is a class that has no instances. An abstract class is written with the
expectation that its concrete subclasses will add to its structure and behaviour, typically by
implementing its abstract operations.
11) What is an Interface?
Interface is an outside view of a class or object which emphaizes its abstraction while
hiding its structure and secrets of its behavior.

12) What is a base class?


Base class is the most generalized class in a class structure. Most applications have such
root classes. In Java, Object is the base class for all classes.

13) What is a subclass?


Subclass is a class that inherits from one or more classes

14) What is a superclass?


superclass is a class from which another class inherits.

15) What is a constructor?


Constructor is an operation that creates an object and/or initialises its state.

16) What is a destructor?


Destructor is an operation that frees the state of an object and/or destroys the object
itself. In Java, there is no concept of destructors. Its taken care by the JVM.

17) What is meant by Binding?


Binding denotes association of a name with a class.

18) What is meant by static binding?


Static binding is a binding in which the class association is made during compile time. This
is also called as Early binding.

19) What is meant by Dynamic binding?


Dynamic binding is a binding in which the class association is not made until the object is
created at execution time. It is also called as Late binding.
20) Define Modularity?
Modularity is the property of a system that has been decomposed into a set of cohesive
and loosely coupled modules.
21) What is meant by Persistence?
Persistence is the property of an object by which its existence transcends space and time.

22) What is collaboration?


Collaboration is a process whereby several objects cooperate to provide some higher level
behavior.

23) In Java, How to make an object completely encapsulated?


All the instance variables should be declared as private and public getter and setter
methods should be provided for accessing the instance variables.

24) How is polymorphism acheived in java?


Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.
JAVA COLLECTIONS INTERVIEW QUESTIONS AND ANSWERS

1) Explain Java Collections Framework?


Java Collections Framework provides a well designed set of interfaces and classes that
support operations on a collections of objects.

2) Explain Iterator Interface.


An Iterator is similar to the Enumeration interface.With the Iterator interface methods, you
can traverse a collection from start to end and safely remove elements from the underlying
Collection. The iterator() method generally used in query operations.
Basic methods:
iterator.remove();
iterator.hasNext();
iterator.next();

3) Explain Enumeration Interface.


The Enumeration interface allows you to iterate through all the elements of a collection.
Iterating through an Enumeration is similar to iterating through an Iterator. However, there is
no removal support with Enumeration.
Basic methods:
boolean hasMoreElements();
Object nextElement();

4) What is the difference between Enumeration and Iterator interface?


The Enumeration interface allows you to iterate through all the elements of a collection.
Iterating through an Enumeration is similar to iterating through an Iterator. However, there is
no removal support with Enumeration.

5) Explain Set Interface.


In mathematical concept, a set is just a group of unique items, in the sense that the group
contains no duplicates. The Set interface extends the Collection interface. Set does not allow
duplicates in the collection. In Set implementations null is valid entry, but allowed only once.

6) What are the two types of Set implementations available in the Collections Framework?
HashSet and TreeSet are the two Set implementations available in the Collections
Framework.

7) What is the difference between HashSet and TreeSet?


HashSet Class implements java.util.Set interface to eliminate the duplicate entries and uses
hashing for storage. Hashing is nothing but mapping between a key value and a data item,
this provides efficient searching.
The TreeSet Class implements java.util.Set interface provides an ordered set, eliminates
duplicate entries and uses tree for storage.

8) What is a List?
List is a ordered and non duplicated collection of objects. The List interface extends the
Collection interface.

9) What are the two types of List implementations available in the Collections Framework?
ArrayList and LinkedList are the two List implementations available in the Collections
Framework.

10) What is the difference between ArrayList and LinkedList?


The ArrayList Class implements java.util.List interface and uses array for storage. An array
storage's are generally faster but we cannot insert and delete entries in middle of the list.To
achieve this kind of addition and deletion requires a new array constructed. You can access
any element at randomly.

The LinkedList Class implements java.util.List interface and uses linked list for storage.A linked
list allow elements to be added, removed from the collection at any location in the container
by ordering the elements.With this implementation you can only access the elements in
sequentially.

11) What collection will you use to implement a queue?


LinkedList

12) What collection will you use to implement a queue?


LinkedList

13) Explain Map Interface.


A map is a special kind of set with no duplicates.The key values are used to lookup, or index
the stored data. The Map interface is not an extension of Collection interface, it has it's own
hierarchy. Map does not allow duplicates in the collection. In Map implementations null is
valid entry, but allowed only once.

14) What are the two types of Map implementations available in the Collections
Framework?
HashMap and TreeMap are two types of Map implementations available in the Collections
Framework.

15) What is the difference between HashMap and TreeMap?


The HashMap Class implements java.util.Map interface and uses hashing for storage.
Indirectly Map uses Set functionality so, it does not permit duplicates. The TreeMap Class
implements java.util.Map interface and uses tree for storage. It provides the ordered map.

16) Explain the functionality of Vector Class?


Once array size is set you cannot change size of the array. To deal with this kind of
situations in Java uses Vector, it grows and shrink it's size automatically. Vector allows to store
only objects not primitives. To store primitives, convert primitives in to objects using wrapper
classes before adding them into Vector.The Vector reallocates and resizes itself automatically.

17) What does the following statement convey?


Vector vt = new Vector(3, 10);
vt is an instance of Vector class with an initial capacity of 3 and grows in increment of 10 in
each relocation

18) How do you store a primitive data type within a Vector or other collections class?
You need to wrap the primitive data type into one of the wrapper classes found in the
java.lang package, like Integer, Float, or Double, as in:
Integer in = new Integer(5);

19) What is the difference between Vector and ArrayList?


Vector and ArrayList are very similar. Both of them represent a gradable array. The main
difference is that Vector is synchronized while ArrayList is not.

20) What is the between Hashtable and HashMap?


Both provide key-value access to data. The key differences are :
a. Hashtable is synchronised but HasMap is not synchronised.
b. HashMap permits null values but Hashtable doent allow null values.
c. iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not fail safe.

21) How do I make an array larger?


You cannot directly make an array larger. You must make a new (larger) array and copy the
original elements into it, usually with System.arraycopy(). If you find yourself frequently doing
this, the Vector class does this automatically for you, as long as your arrays are not of
primitive data types.

22) Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?
Because a synchronized HashMap requires an extra method call, a Hashtable is faster for
synchronized access.

23) In which package would you find the interfaces amd claases defined in the Java
Collection Framework?
java.util
24) What method in the System class allows you to copy elements from one array to
another?
System. arraycopy()

25) When using the System.arraycopy() method,What exception is thrown if the destination
array is smaller than the souce array?
ArrayIndexOutofBoundsException

26) What is the use of Locale class?


The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region

27) What is the use of GregorianCalendar class?


The GregorianCalendar provides support for traditional Western calendars

28) What is the use of SimpleTimeZone class?


The SimpleTimeZone class provides support for a Gregorian calendar

29) What is the use of ResourceBundle class?


The ResourceBundle class is used to store locale-specific resources that can be loaded by a
program to tailor the program's appearance to the particular locale in which it is being run.
APPLETS INTERVIEW QUESTIONS AND ANSWERS

1) What is an Applet?
Applet is a java program which is included in a html page and executes in java enabled
client browser. Applets are used for creating dynamic and interactive web applications.

2) Explain the life cycle of an Applet?


The following methods implement the life cycle of an Applet:
init : To initialize the applet each time it's loaded (or reloaded).
start : To start the applet's execution, such as when the applet's loaded or when the user
revisits a page that contains the applet.
stop : To stop the applet's execution, such as when the user leaves the applet's page or quits
the browser.
destroy : To perform a final cleanup in preparation for unloading.

3) What happens when an applet is loaded?


The following sequence happens when an applet is loaded:
a) An instance of the applet's controlling class (an Applet subclass) is created.
b) The applet initializes itself.
c) The applet starts running.

4) How to make my class as an applet?


Your class must directly or indirectly extend either Applet or JApplet.

5) What is AppletContext?
AppletContext is an interface which provides information about applet's environment.

6) What is the difference between an Applet and a Java Application?


The following are the major differences between an Applet and an Application:
a. Applets execute within a java enabled browser but an application is a standalone Java
program outside of a browser. Both require a JVM (Java Virtual Machine).
b. Application requires main() method to trigger execution but applets doesn't need a main()
method. Applets use the init(),start(),stop() and destroy() methods for their life cycle.
c. Applets typically use a fairly restrictive security policy. In a standalone application, however,
the security policy is usually more relaxed.

7) What happens when a user leaves and returns to an applet's page?


When the user leaves the page, the browser stops the applet and when the user returns to
the page, the browser starts the applet and normally most browser's dont initialise the applet
again..

8) What are the restrictions imposed on an applet?


Due to Security reasons, the following restriction are imposed on applets:
a. An applet cannot load libraries or define native methods.
b. It cannot ordinarily read or write files on the host that's executing it.
c. It cannot make network connections except to the host that it came from.
d. It cannot start any program on the host that's executing it.
e. It cannot read certain system properties.

9) Can a applet invoke public methods of another applet on the same page?
Yes. It's possible.

10) What are untrusted applets?


By default, all downloaded applets are untrusted. Untrusted Applets are those applets
which cannot access or exceute local system files.

11) How to let a downloaded applet to read a file in the local system?
To allow any files in the directory /home/user1 to be read by applets loaded into the
appletviewer, add the following line to your <user home directory>/.hotjava/properties file.
acl.read=/home/user1
You can specify one file to be read:
acl.read=/home/user1/somedir/somefile

12) How to let a downloaded applet to write to a file in the local system?
You can allow applets to write to your /tmp directory by setting the acl.write property in
your <user home directory>/.hotjava/properties file:
acl.write=/tmp
You can allow applets to write to a particular file by naming it explicitly:
acl.write=/home/user1/somedir/somefile

13) How do I hide system properties that applets are allowed to read?
To hide the name of the operating system that you are using, add the following line to your
<user home directory>/.hotjava/properties file:
os.name=null

14) How can I allow applets to read system properties that they aren't allowed to read?
To allow applets to record your user name, add the following line to your <user home
directory>/.hotjava/properties file:
user.name.applet=true

15) How can an applet open a network connection to a computer on the internet?
Applets are not allowed to open network connections to any computer,except for the host
that provided the .class files. This is either the host where the html page came from, or the
host specified in the codebase parameter in the applet tag, with codebase taking
precendence.

16) Can an applet start another program on the client?


No, applets loaded over the net are not allowed to start programs on the client. That is, an
applet that you visit can't start some rogue process on your PC. In UNIX terminology, applets
are not allowed to exec or fork processes. In particular, this means that applets can't invoke
some program to list the contents of your file system, and it means that applets can't invoke
System.exit() in an attempt to kill your web browser. Applets are also not allowed to
manipulate threads outside the applet's own thread group.

17) What is the difference between applets loaded over the net and applets loaded via the
file system?
There are two different ways that applets are loaded by a Java system. The way an applet
enters the system affects what it is allowed to do. If an applet is loaded over the net, then it is
loaded by the applet classloader, and is subject to the restrictions enforced by the applet
security manager. If an applet resides on the client's local disk, and in a directory that is on
the client's CLASSPATH, then it is loaded by the file system loader. The most important
differences are :
a. applets loaded via the file system are allowed to read and write files
b. applets loaded via the file system are allowed to load libraries on the client
c. applets loaded via the file system are allowed to exec processes
d. applets loaded via the file system are allowed to exit the virtual machine
e. applets loaded via the file system are not passed through the byte code verifier

18) What's the applet class loader, and what does it provide?
Applets loaded over the net are loaded by the applet class loader. For example, the
appletviewer's applet class loader is implemented by the class sun.applet.AppletClassLoader.
The class loader enforces the Java name space hierarchy. The class loader guarantees that a
unique namespace exists for classes that come from the local file system, and that a unique
namespace exists for each network source. When a browser loads an applet over the net,
that applet's classes are placed in a private namespace associated with the applet's origin.
Thus, applets loaded from different network sources are partitioned from each other. Also,
classes loaded by the class loader are passed through the verifier.The verifier checks that the
class file conforms to the Java language specification - it doesn't assume that the class file was
produced by a "friendly" or "trusted" compiler. On the contrary, it checks the class file for
purposeful violations of the language type rules and name space restrictions. The verifier
ensures that :
a. There are no stack overflows or underflows.
b. All register accesses and stores are valid.
c. The parameters to all bytecode instructions are correct.
d. There is no illegal data conversion.
e. The verifier accomplishes that by doing a data-flow analysis of the bytecode instruction
stream, along with checking the class file format, object signatures, and special analysis of
finally clauses that are used for Java exception handling.

19) What's the applet security manager, and what does it provide?
The applet security manager is the Java mechanism for enforcing the applet restrictions
described above. The appletviewer's applet security manager is implemented by
sun.applet.AppletSecurity.
A browser may only have one security manager. The security manager is established at
startup, and it cannot thereafter be replaced, overloaded, overridden, or extended. Applets
cannot create or reference their own security manager.

20) If other languages are compiled to Java bytecodes, how does that affect the applet
security model?
The verifier is independent of Sun's reference implementation of the Java compiler and the
high-level specification of the Java language. It verifies bytecodes generated by other Java
compilers. It also verifies bytecodes generated by compiling other languages into the
bytecode format. Bytecodes imported over the net that pass the verifier can be trusted to run
on the Java virtual machine. In order to pass the verifier, bytecodes have to conform to the
strict typing, the object signatures, the class file format, and the predictability of the runtime
stack that are all defined by the Java language implementation.
JAVA LANG PACKAGE INTERVIEW QUESTIONS AND ANSWERS

1) What is the base class of all classes?


java.lang.Object

2) What do you think is the logic behind having a single base class for all classes?
1. casting
2. Hierarchial and object oriented structure.

3) Why most of the Thread functionality is specified in Object Class?


Basically for interthread communication.

4) What is the importance of == and equals() method with respect to String object?
== is used to check whether the references are of the same object.
.equals() is used to check whether the contents of the objects are the same.
But with respect to strings, object refernce with same content
will refer to the same object.

String str1="Hello";
String str2="Hello";

(str1==str2) and str1.equals(str2) both will be true.

If you take the same example with Stringbuffer, the results would be different.
Stringbuffer str1="Hello";
Stringbuffer str2="Hello";

str1.equals(str2) will be true.


str1==str2 will be false.

5) Is String a Wrapper Class or not?


No. String is not a Wrapper class.

6) How will you find length of a String object?


Using length() method of String class.

7) How many objects are in the memory after the exection of following code segment?
String str1 = "ABC";
String str2 = "XYZ";
String str1 = str1 + str2;
There are 3 Objects.
8) What is the difference between an object and object reference?
An object is an instance of a class. Object reference is a pointer to the object. There can be
many refernces to the same object.

9) What will trim() method of String class do?


trim() eliminate spaces from both the ends of a string.***

10) What is the use of java.lang.Class class?


The java.lang.Class class is used to represent the classes and interfaces that are loaded by a
java program.
11) What is the possible runtime exception thrown by substring() method?
ArrayIndexOutOfBoundsException.

12) What is the difference between String and Stringbuffer?


Object's of String class is immutable and object's of Stringbuffer class is mutable moreover
stringbuffer is faster in concatenation.

13) What is the use of Math class?


Math class provide methods for mathametical functions.

14) Can you instantiate Math class?


No. It cannot be instantited. The class is final and its constructor is private. But all the
methods are static, so we can use them without instantiating the Math class.

15) What will Math.abs() do?


It simply returns the absolute value of the value supplied to the method, i.e. gives you the
same value. If you supply negative value it simply removes the sign.

16) What will Math.ceil() do?


This method returns always double, which is not less than the supplied value. It returns next
available whole number

17) What will Math.floor() do?


This method returns always double, which is not greater than the supplied value.

18) What will Math.max() do?


The max() method returns greater value out of the supplied values.

19) What will Math.min() do?


The min() method returns smaller value out of the supplied values.
20) What will Math.random() do?
The random() method returns random number between 0.0 and 1.0. It always returns double.
RMI INTERVIEW QUESTIONS AND ANSWERS

1) What is RMI?
Remote Method Invocation (RMI) is the process of activating a method on a remotely running
object. RMI offers location transparency in the sense that it gives the feel that a method is
executed on a locally running object.

2) What is the basic principle of RMI architecture?


The RMI architecture is based on one important principle: the definition of behavior and the
implementation of that behavior are separate concepts. RMI allows the code that defines the
behavior and the code that implements the behavior to remain separate and to run on
separate JVMs.

3) What are the layers of RMI Architecture?


The RMI is built on three layers.
a. Stub and Skeleton layer
This layer lies just beneath the view of the developer. This layer intercepts method calls made
by the client to the interface reference variable and redirects these calls to a remote RMI
service.

b. Remote Reference Layer.


This layer understands how to interpret and manage references made from clients to the
remote service objects. The connection is a one-to-one (unicast) link.

c. Transport layer
This layer is based on TCP/IP connections between machines in a network. It provides basic
connectivity, as well as some firewall penetration strategies.

4) What is the role of Remote Interface in RMI?


The Remote interface serves to identify interfaces whose methods may be invoked from a
non-local virtual machine. Any object that is a remote object must directly or indirectly
implement this interface. Methods that are to be invoked remotely must be identified in
Remote Interface. All Remote methods should throw RemoteException.

5) What is the role java.rmi.Naming Class?


The Naming class provides methods for storing and obtaining references to remote objects in
the remote object registry.

6) What is the default port used by RMI Registry?


1099

7) What is meant by binding in RMI?


Binding is a process of associating or registering a name for a remote object that can be used
at a later time to look up that remote object. A remote object can be associated with a name
using the Naming class's bind or rebind methods.

8) What is the difference between using bind() and rebind() methods of Naming Class?
bind method(String name) binds the specified name to a remote object while rebind(String
name) method rebinds the specified name to a new remote object,any existing binding for
the name is replaced.

9) When is AlreadyBoundException thrown and by which method?


AlreadyBoundException is thrown by bind(String name) method when a remote object is
already registered with the registry with the same name.
Note: rebind method doesn't throw AlreadyBoundException because it replaces the existing
binding with same name.

10) How to get all the registered objects in a rmiregistry?


Using list method of Naming Class.

11) What are the steps involved to make work a RMI program?
Ans: a. Compile the source files.
b. Generate the stubs using rmic.
c. Start the rmiregistry.
d. Start the RMIServer.
e. Run the client program.

12) What is the role of stub in RMI?


Ans: A stub for a remote object acts as a client's local representative or proxy for the remote
object. The caller invokes a method on the local stub which is responsible for carrying out the
method all on the remote object. When a stub's method is invoked, it does the following:
a. initiates a connection with the remote JVM containing the remote object.
b. marshals (writes and transmits) the parameters to the remote JVM.
c. waits for the result of the method invocation
d. unmarshals (reads) the return value or exception returned
e. returns the value to the caller.

13) What is a skeleton in RMI?


Ans: Skeleton was the server side component of stub. But skeleton has been deprecated from
JDK1.2 onwards and its not required anymore.

14) What is DGC? And how does it work?


Ans: DGC is Distributed Garbage Collection. RMI is uses DGC for automatic garbage collection.
Since RMI involve remote object references across JVM's, garbage collection is a bit tricky.
DGC uses a reference counting algorithm to provide automatic memory management for
remote objects.

15) What is the purpose of using RMISecurityManager in RMI?


Ans: RMISecurityManager provides a security manager for use by RMI applications that use
downloaded code. RMI's class loader will not download any classes from remote locations if
no security manager has been set. The following statment sets it:
System.setSecurityManager(new RMISecurityManager());

16) What is the difference between Pass By Value and Pass By Reference?
Ans: When an Object is "Passed by Value", it means a copy of the object is passed. So even if
changes are made to that Object/datatype, it doesn't affect the original value.
When an Object is "Passed by Refernce", it means the object is not passed but a reference of
the object is passed. so any changes made in the external method gets reflected in all places.

17) In RMI, Objects are passed by Value or Reference?


Ans: In RMI, Objects are Passed by Value.

18) What are marker interfaces?


Ans: A so-called marker interface is a Java interface which doesn't actually define any fields or
methods. It is just used to "mark" Java classes which support a certain capability -- the class
marks itself as implementing the interface. For example, the java.rmi.Remote and
java.lang.Cloneable interface.

19) What do u mean by marshalling and demarshalling?


Ans: When objects in memory are to be passed across a network to another host or persisted
to storage, their in-memory representation must be converted to a suitable out-of-memory
format. This process is called marshalling, and converting back to an in memory
representation is called demarshalling.

20) What is meant by Serialisation and Deserialisation?


Ans: Serialization is a way of "flattening", "pickling" or "freeze-drying" objects so that they can
be stored on disk, and later read back and reconstituted, with all the links between objects
intact. Deserialisation is the reverse process of converting a object from flattened state to live
object.

21) Can a class implementing a Remote interface have non remote methods?
Yes. Those methods behave as normal java methods operating within the JVM.

22) What is the protocol used by RMI?


JRMP(java remote method protocol)
23) What is the use of UnicastRemoteObject in RMI?
The UnicastRemoteObject class provides support for point-to-point active object references
using TCP streams. Objects that require remote behavior should extend
UnicastRemoteObject.

24) What does the exportObject of UnicastRemoteObject do?


Exports the remote object to make it available to receive incoming calls, using the particular
supplied port. If port not specified receives calls from any anonymous port.

25) What is PortableRemoteObject.narrow() method and what is used for?


Java RMI-IIOP provides a mechanism to narrow the the Object you have received from from
your lookup, to the appropriate type. This is done through the
javax.rmi.PortableRemoteObject class and, more specifically, using the narrow() method.

26) In a RMI Client Program, what are the excpetions which might have to handled?
a. MalFormedURLException
b. NotBoundException
c. RemoteException
SERVLETS INTERVIEW QUESTIONS AND ANSWERS

1) What is a Servlet?
A Servlet is a server side java program which processes client requests and generates dynamic web content.

2) Explain the architechture of a Servlet?


javax.servlet.Servlet interface is the core abstraction which has to be implemented by all servlets either directly or
indirectly. Servlet run on a server side JVM ie the servlet container.Most servlets implement the interface by
extending either javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet.A single servlet object serves
multiple requests using multithreading.

3) What is the difference between an Applet and a Servlet?


An Applet is a client side java program that runs within a Web browser on the client machine whereas a servlet is a
server side component which runs on the web server. An applet can use the user interface classes like AWT or
Swing while the servlet does not have a user interface. Servlet waits for client's HTTP requests from a browser and
generates a response that is displayed in the browser.

4) What is the difference between GenericServlet and HttpServlet?


GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet package. Servlets
extending GenericServlet should override service() method. javax.servlet.http.HTTPServlet extends GenericServlet.
HTTPServlet is http protocol specific ie it services only those requests thats coming through http.A subclass of
HttpServlet must override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy() or
getServletInfo().

5) Explain life cycle of a Servlet?


On client's initial request, Servlet Engine loads the servlet and invokes the init() methods to initialize the servlet.
The servlet object then handles subsequent client requests by invoking the service() method. The server removes
the servlet by calling destry() method.

6) What is the difference between doGet() and doPost()?


doGET Method : Using get method we can able to pass 2K data from HTML All data we are passing to Server will be
displayed in URL (request string).

doPOST Method : In this method we does not have any size limitation. All data passed to server will be hidden,
User cannot able to see this info on the browser.

7) What is the difference between ServletConfig and ServletContext?


ServletConfig is a servlet configuration object used by a servlet container to pass information to a servlet during
initialization. All of its initialization parameters can only be set in deployment descriptor. The ServletConfig
parameters are specified for a particular servlet and are unknown to other servlets.The ServletContext object is
contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
ServletContext is an interface which defines a set of methods which the servlet uses to interact with its servlet
container. ServletContext is common to all servlets within the same web application. Hence, servlets use
ServletContext to share context information.

8) What is the difference between using getSession(true) and getSession(false) methods?


getSession(true) method will check whether already a session is existing for the user. If a session is existing, it will
return the same session object, Otherwise it will create a new session object and return taht object.

getSession(false) method will check for the existence of a session. If a session exists, then it will return the
reference of that session object, if not, it will return null.

9) What is meant by a Web Application?


A Web Application is a collection of servlets and content installed under a specific subset of the server's URL
namespace such as /catalog and possibly installed via a .war file.

10) What is a Server Side Include ?


Server Side Include is a Web page with an embedded servlet tag. When the Web page is accessed by a browser, the
web server pre-processes the Web page by replacing the servlet tag in the web page with the hyper text generated
by that servlet.

11) What is Servlet Chaining?


Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the
second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the
Web browser.

12) How do you find out what client machine is making a request to your servlet?
The ServletRequest class has functions for finding out the IP address or host name of the client machine.
getRemoteAddr() gets the IP address of the client machine and getRemoteHost()gets the host name of the client
machine.

13) What is the structure of the HTTP response?


The response can have 3 parts:
1) Status Code - describes the status of the response. For example, it could indicate that the request was
successful, or that the request failed because the resource was not available. If your servlet does not return a
status code, the success status code, HttpServletResponse.SC_OK, is returned by default.
2) HTTP Headers - contains more information about the response. For example, the header could specify the
method used to compress the response body.
3) Body - contents of the response. The body could contain HTML code, an image, etc.

14) What is a cookie?


A cookie is a bit of information that the Web server sends to the browser which then saves the cookie to a file. The
browser sends the cookie back to the same server in every request that it makes. Cookies are often used to keep
track of sessions.
15) Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

16) Which protocol will be used by browser and servlet to communicate ?


HTTP

17) Can we use the constructor, instead of init(), to initialize servlet?


Yes, of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The
original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments,
so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will
only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

18) How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push

19) What is the Max amount of information that can be saved in a Session Object?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM
available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should
not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto
hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the
predefined limit, most of the servers write it to a temporary cache on hard disk.

20) What is HTTP Tunneling?


HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-
network of an organization is blocked by a firewall and the network is exposed to the outer world only through a
specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall,
the protocol is embedded in HTTP and sent as HttpRequest. The masking of other protocol requests as http
requests is HTTP Tunneling.

21) What's the difference between sendRedirect( ) and forward( ) methods?


A sendRedirect method creates a new request (it's also reflected in browser's URL ) where as forward method
forwards the same request to the new target(hence the change is NOT reflected in browser's URL). The previous
request scope objects are no longer available after a redirect because it results in a new request, but it's available
in forward. sendRedirect is slower compared to forward.

22) Is there some sort of event that happens when a session object gets bound or unbound to the session?
HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object,
or when the session is invalidated, in which case the objects are first removed from the session, whether the
session is invalidated manually or automatically (timeout).

23) Is it true that servlet containers service each request by creating a new thread? If that is true, how does a
container handle a sudden dramatic surge in incoming requests without significant performance degradation?
The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to
give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a
request, they simply borrow a thread from the pool and when they are done, return it to the pool. For this thread
pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem
associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle
threads, freeing them if needed.

25) What is URL Encoding and URL Decoding?


URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex
Characters and Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL,
/ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F
This can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")

26) Do objects stored in a HTTP Session need to be serializable? Or can it store any object?
Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most
lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even
if your engine does support persistent sessions, it is usually possible to disable this feature.

27) What is the difference between session and cookie?


The difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie
(through browser settings) session still works. There is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. Javax.servlet.http.HttpSession has a
setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession
is capable of storing any java object. Cookie can only store String objects.

28) How to determine the client browser version?


Another name for "browser" is "user agent." You can read the User-Agent header using request.getUserAgent() or
request.getHeader("User-Agent")
JSP INTERVIEW QUESTIONS AND ANSWERS

1) Briefly explain about Java Server Pages technology?


JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated
content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the
interaction between the server and the JSP page, and describes the format and syntax of the page.

2) What is a JSP Page?


A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format
(such as HTML,WML,XML,etc), and JSP elements, which construct dynamic content.JSP is a technology that lets you mix
static content with dynamically-generated content.

3) Why do I need JSP technology if I already have servlets?


JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications.
However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web
content. In many applications, the response sent to the client is a combination of template data and dynamically-generated
data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

4) How are the JSP requests handled?


The following sequence of events happens on arrival of jsp request:
a. Browser requests a page with .jsp file extension in webserver.
b. Webserver reads the request.
c. Using jsp compiler,webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page
interface.the jsp file compiles only when the page is first requested or when the jsp file has been changed.
d. The generated jsp page servlet class is invoked to handle the browser request.
e. The response is sent to the client by the generated servlet.

5) What are the advantages of JSP?


Ans : The following are the advantages of using JSP:
a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.

b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to
presentation code. JSP pages can also be precompiled if desired.
c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the
complexity of application logic.
d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly,
developers can make logic changes at the component level without editing the individual pages that use the logic.

6) How is a JSP page invoked and compiled?


Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time
the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the
page have very fast response times.

7) What are Directives?


Directives are instructions that are processed by the JSP engine when the page is compiled to a servlet. Directives are used
to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined
between < %@ and % >.
< %@ page language=="java" imports=="java.util.*" % >
< %@ include file=="banner.html" % >

8) What are the different types of directives available in JSP?


Ans : The following are the different types of directives:
a. include directive : used to include a file and merges the content of the file with the current page
b. page directive : used to define page specific attributes like scripting language, error page, buffer, thread safety, etc
c. taglib : used to declare a custom tag library which is used in the page.

9) What are JSP actions?


JSP actions are executed when a JSP page is requested. Action are inserted in the jsp page using XML syntax to control the
behavior of the servlet engine. Using action, we can dynamically insert a file, reuse bean components, forward the user to
another page, or generate HTML for the Java plugin. Some of the available actions are as follows:
<jsp:include> - include a file at the time the page is requested.
<jsp:useBean> - find or instantiate a JavaBean.
<jsp:setProperty> - set the property of a JavaBean.
<jsp:getProperty> - insert the property of a JavaBean into the output.
<jsp:forward> - forward the requester to a new page.
<jsp:plugin> - generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

10) What are Scriptlets?


Scriptlets are blocks of programming language code (usually java) embedded within a JSP page. Scriptlet code is inserted
into the servlet generated from the page. Scriptlet code is defined between <% and %>

11) What are Decalarations?


Declarations are similar to variable declarations in Java.Variables are defined for subsequent use in expressions or
scriptlets. Declarations are defined between <%! and %>.
< %! int i=0; %>

12) How to declare instance or global variables in jsp?


Instance variables should be declared inside the declaration part. The variables declared with JSP declaration element will
be shared by all requests to the jsp page.
< %@ page language=="java" contentType="text/html"% >
< %! int i=0; %>
13) What are Expressions?
Expressions are variables or constants that are inserted into the data returned by the web server. Expressions are defined
between <% = and % >
< %= scorer.getScore() %>

14) What is meant by implicit objects? And what are they?


Ans : Implicit objects are those objects which are avaiable by default. These objects are instances of classesdefined by the
JSP specification. These objects could be used within the jsp page without being declared.

The following are the implicit jsp objects:


1. application
2. page
3. request
4. response
5. session
6. exception
7. out
8. config
9. pageContext

15) How do I use JavaBeans components (beans) from a JSP page?


The JSP specification includes standard tags for bean use and manipulation. The <jsp:useBean> tag creates an instance of a
specific JavaBean class. If the instance already exists, it is retrieved. Otherwise, a new instance of the bean is created. The
<jsp:setProperty> and <jsp:getProperty> tags let you manipulate properties of a specific bean.

16) What is the difference between <jsp:include> and <%@include:>


Both are used to insert files into a JSP page.
<%@include:> is a directive which statically inserts the file at the time the JSP page is translated into a servlet.
<jsp:include> is an action which dynamically inserts the file at the time the page is requested.

17) What is the difference between forward and sendRedirect?


Both requestDispatcher.forward() and response.sendRedirect() is used to redirect to new url.

forward is an internal redirection of user request within the web container to a new URL without the knowledge of the
user(browser). The request object and the http headers remain intact.

sendRedirect is normally an external redirection of user request outside the web container. sendRedirect sends response
header back to the browser with the new URL. The browser send the request to the new URL with fresh http headers.
sendRedirect is slower than forward because it involves extra server call.

18) Can I create XML pages using JSP technology?


Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be
included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or
custom tags that generate XML output.

19) How is Java Server Pages different from Active Server Pages?
JSP is a community driven specification whereas ASP is a similar proprietary technology from Microsoft. In JSP, the dynamic
part is written in Java, not Visual Basic or other MS-specific language. JSP is portable to other operating systems and non-
Microsoft Web servers whereas it is not possible with ASP

20) Can't Javascript be used to generate dynamic content rather than JSP?
JavaScript can be used to generate dynamic content on the client browser. But it can handle only handles situations where
the dynamic information is based on the client's environment. It will not able to harness server side information directly.
EJB INTERVIEW QUESTIONS AND ANSWERS

1) What are Enterprise Java Beans?


Enterprise Java Beans (EJB) is a specification which defines a component architecture for
developing distributed systems. Applications written using the Enterprise JavaBeans
architecture are resusable,scalable, transactional, and secure. Enterprise Java Bean's allow
the developer to only focus on implementing the business logic of the application.

3) How many types of Enterprise beans are there and what are they?
There are 3 types EJB's and they are:
1. Entity Bean's
2. Session Bean's
3. Message Driven Bean's(MDB's)

4) How many types of Entity beans are there and what are they?
There are 2 types Entity bean's and they are:
1. Container Managed Persistence(CMP) Entity Bean's
2. Bean Managed Persistence(BMP) Entity Bean's

5) How many types of Session beans are there and what are they?
There are 2 types Session bean's and they are:
1. Statefull Session Bean's
2. Stateless Session Bean's

6) How many types of MDB's are there and what are they?
There are no different kinds of Message driven beans.

2) How is a enterprise bean different from a java bean?


Both the enterprise bean and the java bean are designed to be highly reusable. But other
than being reusable there is no similarity between them. Java bean is mostly a simple client-
side component whereas enterprise bean is a complex server side component.

7) How many java files should a developer code to develop a session bean?
3 java files has to be provided by the developer. They are:
1) an Home Interface
2) a Remote Interface
3) And a Session Bean implementation class.

8) Explain the role of Home Interface.


Home interface contains factory methods for locating, creating and removing instances of
EJB's.
9) Explain the role of Remote Interface.
Remote interface defines the business methods callable by a client. All methods defined in
the remote interface must throw RemoteException.

10) What is the need for a separate Home interface and Remote Interface. Can't they be
defined in one interface?
EJB doesn't allow the client to directly communicate with an enterprise bean. The client has
to use home and remote interfaces for any communication with the bean.
The Home Interface is for communicating with the container for bean's life cycle operations
like creating, locating,removing one or more beans. While the remote interface is used for
remotely accessing the business methods.

11) What are callback methods?


Callback methods are bean's methods, which are called by the container. These are called to
notify the bean, of it's life cycle events.

12) How will you make a session bean as stateful or stateless?


We have to specify the it in the deployment descriptor(ejb-jar.xml) using <session-type> tag.

13) What is meant by Activation?


The process of transferring an enterprise bean from secondary storage to memory.

14) What is meant by Passivation?


The process of transferring an enterprise bean from memory to secondary storage.

15) What is a re-entrant Entity Bean?


An re-entrant Entity Bean is one that can handle multiple simultaneous, interleaved, or
nested invocations which will not interfere with each other.

16) Why are ejbActivate() and ejbPassivate() included for stateless session bean even
though they are never required as it is a nonconversational bean?
To have a consistent interface, so that there is no different interface that you need to
implement for Stateful Session Bean and Stateless Session Bean. Both Stateless and Stateful
Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless
session bean is to remove ejbActivate and ejbPassivate from the interface.

17) What is an EJBContext?


EJBContext is an object that allows an enterprise bean to invoke services provided by the
container and to obtain the information about the caller of a client-invoked method.

18) Explain the role of EJB Container?


EJB Container implements the EJB component contract of the J2EE architecture. It provides a
runtime environment for enterprise beans that includes security, concurrency, life cycle
management, transactions, deployment, naming, and other services. An EJB Container is
provided by an EJB Server.

19) What are Entity Bean's?


Entity Bean is an enterprise bean that represents persistent data maintained in a database.
An entity bean can manage its own persistence or can delegate this function to its container.
An entity bean is identified by a primary key. If the container in which an entity bean is hosted
crashes, the entity bean, its primary key, and any remote references survive the crash.

20) What is a Primary Key?


Primary Key is an object that uniquely identifies an entity bean within a home.

20) Can we specify primitive data type be as a primary key?


Primitive data type cannot be directly used as primary key, it should be wrapped using a
wrapper class.

21) What is a Deployment Descriptor?


Deployment Descriptor is a XML file provided with each module and application that
describes how they should be deployed. The deployment descriptor directs a deployment
tool to deploy a module or application with specific container options and describes specific
configuration requirements that a deployer must resolve.

22) What are the new features that were introduced in EJB version 2.0 specification?
1. New CMP Model. It is based on a new contract called the abstract persistence schema,
that will allow to the container to handle the persistence automatically at runtime.
2. EJB Query Language. It is a sql-based language that will allow the new persistence schema
to implement and execute finder methods.
3. Message Driven Beans. It is a new bean type, that is introduced to handle asynchronous
messaging.
4. Local interfaces. Enabales beans in the same EJB Container to communicate directly.
5. ejbHome methods. Entity beans can declare ejbHome methods that perform operations
related to the EJB component but that are not specific to a bean instance.

23) What are the difference's between a Local Interface and a Remote Interface?
Local Interfaces are new mechanism introduced in EJB 2.0 specification which enables
components in the same container to bypass RMI and call each other's methods directly. In
general, direct local method calls are faster than remote method calls. The downside is a loss
of flexibility: because bean and client must run in the same container, the location of the
bean is not transparent to the client (as it is with remote interfaces). remote interfaces pass
parameters by value, while local interfaces pass them by reference.

24) Can a bean be defined both as a Local and a Remote?


Yes.

25) What are ejbHome methods or Home Business Methods?


EJB 2.0 allows entity beans to declare ejbHome methods in the home interface. These
methods perform operations that are not specific to a particular bean instance.

26) What is a transaction?


A transaction is a sequence of operations that must all complete successfully, or leave system
in the state it had been before the transaction started.

27) What do mean by ACID properties of a transaction?


ACID is the acronym for the four properties guaranteed by transactions: atomicity,
consistency, isolation, and durability.

28) Where will you mention whether the transaction is container managed or bean
managed?
Transaction management is specified in the deployment descriptor(ejb-jar.xml) using
<transaction-type> tag.

29) What are container managed transactions?


In an enterprise bean with container-managed transactions, the EJB container sets the
boundaries of the transactions. You can use container-managed transactions with any type of
enterprise bean: session, entity, or message-driven. Container-managed transactions simplify
development because the enterprise bean code does not explicitly mark the transaction's
boundaries. The code does not include statements that begin and end the transaction.

30) What methods are restricted being called inside a method decalred as container
managed?
We should not invoke any method that might interfere with the transaction boundaries set by
the container. The list of restricted methods are as follows:
1) The commit, setAutoCommit, and rollback methods of java.sql.Connection
2) The getUserTransaction method of javax.ejb.EJBContext
3) Any method of javax.transaction.UserTransaction

31) What are bean managed transactions?


For bean-managed transactions, the bean specifies transaction demarcations using methods
in the javax.transaction.UserTransaction interface. Bean-managed transactions include any
stateful or stateless session beans with a transaction-type set to Bean. Entity beans cannot
use bean-managed transactions.

For stateless session beans, the entering and exiting transaction contexts must match. For
stateful session beans, the entering and exiting transaction contexts may or may not match. If
they do not match, EJB container maintains associations between the bean and the
nonterminated transaction.

Session beans with bean-managed transactions cannot use the setRollbackOnly and
getRollbackOnly methods of the javax.ejb.EJBContext interface.

32) What is the difference between container managed and bean managed transaction?
In container-managed transaction, the transaction boundaries are defined by the container
while in bean managed transaction, the transaction boundaries are defined by the bean.
Entity Beans transactions are always container managed.

32) Why entity bean's transaction can't be managed by the bean?


Entity bean's represent the data and responsible for the integrity of the data. Entity bean's
doesn't represent business operations to manage transactions. So there is no requirement for
an entity bean managing it's transaction.

33) How many types of transaction attributes are available in EJB and what are they?
There 6 types of Transaction Atributes defined in EJB. They are as follows:
1. NotSupported : If the method is called within a transaction, this transaction is suspended
during the time of the method execution.
2. Required : If the method is called within a transaction, the method is executed in the scope
of this transaction; otherwise, a new transaction is started for the execution of the method
and committed before the method result is sent to the caller.
3. RequiresNew : The method will always be executed within the scope of a new transaction.
The new transaction is started for the execution of the method, and committed before the
method result is sent to the caller. If the method is called within a transaction, this
transaction is suspended before the new one is started and resumed when the new
transaction has completed.
4. Mandatory: The method should always be called within the scope of a transaction, else the
container will throw the TransactionRequired exception.
5. Supports : The method is invoked within the caller transaction scope; if the caller does not
have an associated transaction, the method is invoked without a transaction scope.
6. Never : The client is required to call the bean without any transaction context; if it is not
the case, a java.rmi.RemoteException is thrown by the container.

34) How many types of Isolation Level's are available in EJB and what are they?
35) Are we allowed to change the transaction isolation property in middle of a transaction?
No. You cannot change the transaction isolation level in the middle of transaction.

36) Are enterprise beans allowed to use Thread.sleep()?


Enterprise beans are restricted from invoking multithreading thread functionality.

37) Can a bean be attached to more than one JNDI name?


Yes. A same bean can be deployed multiple times in the same server with different JNDI
names.

38) Can a client program directly access an Enterprise bean?


No. EJB Clients never access an EJB directly. The container insulates the beans from direct
access from client applications. Every time a bean is requested, created, or deleted, the
container manages the whole process.

39) When is an application said to be distributed?


An application is distributed when its components are running in separate runtime
environments(JVM's), usually on different platforms connected via a network.
Distributed applications are usually of 3 types. They are :
1. two tier (client and a server)
2.three tier (client and a middleware and a server)
3. multitier (client and multiple middleware and multiple servers).

40) What is an EAR file?


EAR is Enterprise Archive file. A archive file that contains a J2EE application.

41) What do mean by business method?


A method of an enterprise bean that implements the business logic or rules of an application.

42) What is a finder method?


A method defined in the home interface and invoked by a client to locate an entity bean.

Das könnte Ihnen auch gefallen