OOPS Interview Questions


OOPS Interview Questions

 

  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 behaviour.
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, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

  1. 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 focussing 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 behaviour.
12.What is a base class?

Base class is the most generalised 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 colloboration?

Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.
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.

Exception Handling Interview Questions & Answers

Which package contains exception handling related classes?

 

java.lang

What are the two types of Exceptions?

 

Checked Exceptions and Unchecked Exceptions.

What is the base class of all exceptions?

 

java.lang.Throwable

What is the difference between Exception and Error in java?

 

Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

What is the difference between throw and throws?

 

throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

Differentiate between Checked Exceptions and Unchecked Exceptions?

 

Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it’s subclasses, Error and it’s subclasses fall under unchecked exceptions.

What are User defined Exceptions?

 

Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

What is the importance of finally block in exception handling?

 

Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

Can a catch block exist without a try block?

 

No. A catch block should always go with a try block.

Can a finally block exist with a try block but without a catch?

 

Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

What will happen to the Exception object after exception handling?

 

Exception object will be garbage collected.

The subclass exception should precede the base class exception when used within the catch clause. True/False?

 

True.

Exceptions can be caught or rethrown to a calling method. True/False?

 

True.

The statements following the throw keyword in a program are not executed. True/False?

 

True.

How does finally block differ from finalize() method?

 

Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

What are the constraints imposed by overriding on exception handling?

 

An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.

Java Threads Interview Questions & Answers

What are the two types of multitasking?

 

  1. Process-based.b. Thread-based.

What is a Thread?

 

A thread is a single sequential flow of control within a program.

What are the two ways to create a new thread?

 

a.Extend the Thread class and override the run() method.b.Implement the Runnable interface and implement the run() method.

If you have ABC class that must subclass XYZ class, which option will you use to create a thread?

 

I will make ABC implement the Runnable interface to create a new thread, because ABC class will not be able to extend both XYZ class and Thread class.

Which package contains Thread class and Runnable Interface?

 

java.lang package

What is the signature of the run() mehod in the Thread class?

 

public void run()

Which methods calls the run() method?

 

start() method.

Which interface does the Thread class implement?

 

Runnable interface

What are the states of a Thread ?

 

Ready,Running,Waiting and Dead.

Where does the support for threading lie?

 

The thread support lies in java.lang.Thread, java.lang.Object and JVM.

In which class would you find the methods sleep() and yield()?

 

Thread class

In which class would you find the methods notify(),notifyAll() and wait()?

 

Object class

What will notify() method do?

 

notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which thread will be moved out of the pool.

Can you notify a particular thread?

 

No.

What is the difference between sleep() and yield()?

 

When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield() method, it returns to the ready state.

What is a Daemon Thread?

 

Daemon is a low priority thread which runs in the backgrouund.

How to make a normal thread as daemon thread?

 

We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

What is the difference between normal thread and daemon thread?

 

Normal threads do mainstream activity, whereas daemon threads are used low priority work. Hence daemon threads are also stopped when there are no normal threads.

Give one good example of a daemon thread?

 

Garbage Collector is a low priority daemon thread.

What does the start() method of Thread do?

 

The thread’s start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run () method.

What are the two ways that a code can be synchronised?

 

  1. Method can be declared as synchronised.b. A block of code be sychronised.

Can you declare a static method as synchronized?

 

Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.

Can a thread execute another objects run() method?

 

A thread can execute it’s own run() method or another objects run() method.

What is the default priority of a Thread?

 

NORM_PRIORITY

What is a deadlock?

 

A condition that occurs when two processes are waiting for each other to complete before proceeding. The result is that both processes wait endlessly.

What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?

 

  1. wait(),notify() & notifyall()b. Object class

What is the mechanisam defind in java for a code segment be used by only one Thread at a time?

 

Synchronisation

What is the procedure to own the moniter by many threads?

 

Its not possible. A monitor can be held by only one thread at a time.

What is the unit for 500 in the statement, obj.sleep(500);?

 

500 is the no of milliseconds and the data type is long.

What are the values of the following thread priority constants?
MAX_PRIORITY,MIN_PRIORITY and NORMAL_PRIORITY

 

10,1,5

What is the default thread at the time of starting a java application?

 

main thread

The word synchronized can be used with only a method. True/ False?

 

False. A block of code can also be synchronised.

What is a Monitor?

 

A monitor is an object which contains some synchronized code in it.

What are all the methods defined in the Runnable Interface?

 

only run() method is defined the Runnable interface.

How can i start a dead thread?

 

A dead Thread cannot be started again.

When does a Thread die?

 

A Thread dies after completion of run() method.

What does the yield() method do?

 

The yield() method puts currently running thread in to ready state.

What exception does the wait() method throw?

 

The java.lang.Object class wait() method throws “InterruptedException”.

What does notifyAll() method do?

 

notifyAll() method moves all waiting threads from the waiting pool to ready state.

What does wait() method do?

 

wait() method releases CPU, releases objects lock, the thread enters into pool of waiting threads.

Java Collections Interview Questions & Answers

Explain Java Collections Framework?

 

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

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();

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();

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.

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.

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.

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.

What is a List?

 

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

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.

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.

What collection will you use to implement a queue?

 

LinkedList

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.

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.

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.

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.

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

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);

What is the difference between Vector and ArrayList?

 

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

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.

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.

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.

In which package would you find the interfaces amd claases defined in the Java Collection Framework?

 

java.util

What method in the System class allows you to copy eleemnts from one array to another?

 

System. arraycopy()

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

What is the use of GregorianCalendar class?

 

The GregorianCalendar provides support for traditional Western calendars

What is the use of SimpleTimeZone class?

 

The SimpleTimeZone class provides support for a Gregorian calendar

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.

Swing Interview Questions & Answers

What is the difference between a Choice and a List?

 

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

What interface is extended by AWT event listeners?

 

All AWT event listeners extend the java.util.EventListener interface.

What is a layout manager?

 

A layout manager is an object that is used to organize components in a container.

Which Component subclass is used for drawing and painting?

 

Canvas

What is the difference between a Scrollbar and a ScrollPane?

 

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Which Swing methods are thread-safe?

 

The only thread-safe methods are repaint(), revalidate(), and invalidate()

Which containers use a border Layout as their default layout?

 

The Window, Frame and Dialog classes use a border layout as their default layout

What is the preferred size of a component?

 

The preferred size of a component is the minimum component size that will allow the component to display normally

Which containers use a FlowLayout as their default layout?

 

The Panel and Applet classes use the FlowLayout as their default layout

What is the immediate superclass of the Applet class?

 

Panel

Name three Component subclasses that support painting.

 

The Canvas, Frame, Panel, and Applet classes support painting

What is the immediate superclass of the Dialog class?

 

Window

What is clipping?

 

Clipping is the process of confining paint operations to a limited area or shape.

What is the difference between a MenuItem and a CheckboxMenuItem?

 

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

What class is the top of the AWT event hierarchy?

 

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy

In which package are most of the AWT events that support the event-delegation model defined?

 

Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

Which class is the immediate superclass of the MenuComponent class?

 

Object

Which containers may have a MenuBar?

 

Frame

What is the relationship between the Canvas class and the Graphics class?

 

A Canvas object provides access to a Graphics object via its paint() method.

How are the elements of a BorderLayout organized?

 

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

What is the difference between a Window and a Frame?

 

The Frame class extends Window to define a main application window that can have a menu bar.

What is the difference between the Font and FontMetrics classes?

 

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

How are the elements of a CardLayout organized?

 

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

What is the relationship between clipping and repainting?

 

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

What is the relationship between an event-listener interface and an event-adapter class?

 

An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

How can a GUI component handle its own events?

 

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

How are the elements of a GridBagLayout organized?

 

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

What advantage do Java’s layout managers provide over traditional windowing systems?

 

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

What is the difference between the paint() and repaint() methods?

 

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

How can the Checkbox class be used to create a radio button?

 

By associating Checkbox objects with a CheckboxGroup

Difference between paint() and paintComponent()?

 

The key point is that the paint() method invokes three methods in the following order:

  • paintComponent()
  • paintBorder()
  • paintChildren()

As a general rule, in Swing, you should be overriding the paintComponent method unless you know what you are doing. paintComponent() paints only component (panel) but paint() paints component and all its children.

What is the difference between paint(), repaint() and update() methods within an applet which contains images?

 

paint : is only called when the applet is displayed for the first time, or when part of the applet window has to be redisplayed after it was hidden.
repaint : is used to display the next image in a continuous loop by calling the update method.
update : you should be aware that, if you do not implement it yourself, there is a standard update method that does the following : it will reset the applet window to the current background color (i.e. it will erase the current image) it will call paint to construct the new image

What is the name of the design pattern that Java uses for all Swing components?

 

MVC(Model View Controller) pattern

Name few LayoutManagers in Java.

 

  • Flow Layout Manager
  • Grid Layout Manager
  • Border Layout Manager
  • Box Layout Manager
  • Card Layout Manager
  • GridBag Layout Manager

GC Interview Questions & Answers

Explain Garbage collection in Java?

 

In Java, Garbage Collection is automatic. Garbage Collector Thread runs as a low priority daemon thread freeing memory.

When does the Garbage Collection happen?

 

When there is not enough memory. Or when the daemon GC thread gets a chance to run.

When is an Object eligible for Garbage collection?

 

An Object is eligble for GC, when there are no references to the object.

What are two steps in Garbage Collection?

 

  1. Detection of garbage collectible objects and marking them for garbage collection.
  2. Freeing the memory of objects marked for GC.

What is the purpose of finalization?

 

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Can GC be forced in Java?

 

No. GC can’t be forced.

What does System.gc() and Runtime.gc() methods do?

 

These methods inform the JVM to run GC but this is only a request to the JVM but it is up to the JVM to run GC immediately or run it when it gets time.

When is the finalize() called?

 

finalize() method is called by the GC just before releasing the object’s memory. It is normally advised to release resources held by the object in finalize() method.

Can an object be resurrected after it is marked for garbage collection?

 

Yes. It can be done in finalize() method of the object but it is not advisable to do so.

Will the finalize() method run on the resurrected object?

 

No. finalize() method will run only once for an object. The resurrected object’s will not be cleared till the JVM cease to exist.

GC is single threaded or multi threaded?

 

Garbage Collection is multi threaded from JDK1.3 onwards.

What are the good programming practices for better memory management?

 

  • We shouldn’t declare unwanted variables and objects.
  • We should avoid declaring variables or instantiating objects inside loops.
  • When an object is not required, its reference should be nullified.
  • We should minimize the usage of String object and SOP’s.

When is the Exception object in the Exception block eligible for GC?

 

Immediately after Exception block is executed.

When are the local variables eligible for GC?

 

Immediately after method’s execution is completed.

If an object reference is set to null, Will GC immediately free the memory held by that object?

 

No. It will be garbage collected only in the next GC cycle.

Applets Interview Questions & Answers

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.

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.

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.

How to make my class as an applet?

 

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

What is AppletContext?

 

AppletContext is an interface which provides information about applet’s environment.

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 don’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.

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 initialize the applet again..

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.

Can a applet invoke public methods of another applet on the same page?

 

Yes. It’s possible.

What are untrusted applets?

 

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

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

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

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

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

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.

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.

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

What is 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.

What is 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.

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.

Lang Package Interview Questions & Answers

What is the base class of all classes?

 

java.lang.Object

What do you think is the logic behind having a single base class for all classes?

 

  • casting
  • Hierarchial and object oriented structure.

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.

Is String a Wrapper Class or not?

 

No. String is not a Wrapper class.

How will you find length of a String object?

 

Using length() method of String class.

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.

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.

What will trim() method of String class do?

 

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

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.

What is the possible runtime exception thrown by substring() method?

 

ArrayIndexOutOfBoundsException.

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.

What is the use of Math class?

 

Math class provide methods for mathametical functions.

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.

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.

What will Math.ceil() do?

 

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

What will Math.floor() do?

 

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

What will Math.max() do?

 

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

What will Math.min() do?

 

The min() method returns smaller value out of the supplied values.

What will Math.random() do?

 

The random() method returns random number between 0.0 and 1.0. It always returns double.

JDBC Interview Questions & Answers

What is JDBC?

 

JDBC is a layer of abstraction that allows users to choose between databases. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.

How many types of JDBC Drivers are present and what are they?

 

There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

Explain the role of Driver in JDBC?

 

The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

Is java.sql.Driver a class or an Interface?

 

It’s an interface.

Is java.sql.DriverManager a class or an Interface?

 

It’s a class. This class provides the static getConnection method, through which the database connection is obtained.

Is java.sql.Connection a class or an Interface?

 

java.sql.Connection is an interface. The implmentation is provided by the vendor specific Driver.

Is java.sql.Statement a class or an Interface?

 

java.sql.Statement,java.sql.PreparedStatement and java.sql.CallableStatement are interfaces.

Which interface do PreparedStatement extend?

 

java.sql.Statement

Which interface do CallableStatement extend?

 

CallableStatement extends PreparedStatement.

What is the purpose Class.forName(“”) method?

 

The Class.forName(“”) method is used to load the driver.

Do you mean that Class.forName(“”) method can only be used to load a driver?

 

The Class.forName(“”) method can be used to load any class, not just the database vendor driver class.

Which statement throws ClassNotFoundException in SQL code block? and why?

 

Class.forName(“”) method throws ClassNotFoundException. This exception is thrown when the JVM is not able to find the class in the classpath.

What exception does Class.forName() throw?

 

ClassNotFoundException.

What is the return type of Class.forName() method?

 

java.lang.Class

Can an Interface be instantiated? If not, justify and explain the following line of code:
Connection con = DriverManager.getConnection(“dbURL”,”dbUserId”,”dbPassword”);

 

An interface cannot be instantiated. But reference can be made to a interface. When a reference is made to interface, the refered object should have implemented all the abstract methods of the interface. In the above mentioned line, DriverManager.getConnection method returns Connection Object with implementation for all abstract methods.

What type of a method is getConnection()?

 

static method.

What is the return type for getConnection() method?

 

Connection object.

What is the return type for executeQuery() method?

 

ResultSet

What is the return type for executeUpdate() method and what does the return type indicate?

 

int. It indicates the no of records affected by the query.

What is the return type for execute() method and what does the return type indicate?

 

boolean. It indicates whether the query executed sucessfully or not.

Is Resultset a Class or an interface?

 

Resultset is an interface.

What is the advantage of PrepareStatement over Statement?

 

PreparedStatements are precompiled and so performance is better.PreparedStatement objects can be reused with passing different values to the queries.

What is the use of CallableStatement?

 

CallableStatement is used to execute Stored Procedures.

Name the method, which is used to prepare CallableStatement?

 

CallableStament.prepareCall().

What do mean by Connection pooling?

 

Opening and closing of database connections is a costly(resource intensive).So a pool of database connections is obtained at start up by the application server and maintained in a pool.When there is a request for a connection from the application, the application server gives the connection from the pool and when closed by the application is returned back to the pool. Min and max size of the connection pool is configurable. This technique provides better handling of database connectivity.

RMI Interview Questions & Answers

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.

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.

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.

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.

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.

What is the default port used by RMI Registry?

 

1099

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 Namingclass’s bind or rebind methods.

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.

When is AlreadyBoundException thrown and by which method?

 

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

How to get all the registered objects in a rmiregistry?

 

Using list method of Naming Class.

What are the steps involved to make work a RMI program?

 

  1. Compile the source files.
    b. Generate the stubs using rmic.
    c. Start the rmiregistry.
    d. Start the RMIServer.
    e. Run the client program.

What is the role of stub in RMI?

 

A stub for a remote object acts as a client’s local representative orproxy for the remote object. The caller invokes a method onthe 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.

What is a skeleton in RMI?

 

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

What is DGC? And how does it work?

 

DGC is Distributed Garbage Collection. RMI 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.

What is the purpose of using RMISecurityManager in RMI?

 

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 hasbeen set. The following statment sets it:
System.setSecurityManager(new RMISecurityManager());

What is the difference between Pass By Value and Pass By Reference?

 

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.

What are marker interfaces?

 

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.

Explain Marshalling and demarshalling?

 

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.

What is meant by Serialisation and Deserialisation?

 

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.

Can a class implementing a Remote interface have non remote methods?

 

Yes. Those methods behave as normal java methods operating within the JVM.

What is the protocol used by RMI?

 

JRMP(java remote method protocol)

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.

What does the exportO bject 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.

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.

In a RMI Client Program, what are the excpetions which might have to handled?

 

  1. MalFormedURLException
    b. NotBoundException
    c. RemoteException

Servlets Interview Questions & Answers

What is a Servlet?

 

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

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.

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.

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().

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Which code line must be set before any of the lines that use the PrintWriter?

 

setContentType() method must be set.

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

 

HTTP

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.

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.

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.

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.

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).

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.

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”)

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.

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.

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 & Answers

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.

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.

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.

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.

What are the advantages of JSP?

 

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.

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.

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” % >

What are the different types of directives available in JSP?

 

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.

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.

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 %>

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; %>

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; %>

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() %>

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

 

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

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.

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.

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.

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.

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

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.

How do I prevent the output of my JSP or servlet pages from being caches by the browser?

 

Set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Execute the following scriptlet at the beginning of JSP pages to prevent them from being caches at the browser.

<%
response.setHeader(“Cache-Control”,â€?no-storeâ€?); //HTTP 1.1
response.setHeader(“Pragma�,�no-cache�); //HTTP 1.0
response.setDateHeader (“Expires�, 0); //prevents caching at the proxy server
%>

JSF Interview Questions & Answers

Explain about JSF?

 

JSF server side user interface component framework for Javaâ„¢ technology-based web applications.Java Server Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications.

JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.

What are the advantages of JSF?

 

The major benefits of JavaServer Faces technology are:

 

  • Java Server Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
  • Offers a clean separation between behavior and presentation.
  • Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
  • Robust event handling mechanism.
  • Events easily tied to server-side code.
  • Render kit support for different clients
  • Component-level control over statefulness
  • Highly pluggable – components, view handler, etc
  • JSF also supports internationalization and accessibility
  • Offers multiple, standardized vendor implementations

What are differences between struts and JSF?

 

In a nutshell, Faces has the following advantages over Struts:

 

  • Eliminated the need for a Form Bean
  • Eliminated the need for a DTO Class
  • Allows the use of the same POJO on all Tiers because of the Backing Bean

The primary advantages of Struts as compared to JavaServer Faces technology are as follows:

 

  • Because Struts is a web application framework, it has a more sophisticated controller architecture than does JavaServer Faces technology. It is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller. In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.
  • Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application.
  • The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file. You can also create custom validators and easily include them in your application by adding definitions of them in your configuration file.

The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:
[list]

  • A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly av

What are the available implementations of JavaServer Faces?

 

The main implementations of Java Server Faces are:

  • Reference Implementation (RI) by Sun Microsystems.
  • Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
  • ADF Faces is Oracle’s implementation for the JSF standard.

What does a typical JSF application consists of?

 

A typical JSF application consists of the following parts:

 

  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).
  • Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

What Is a JavaServer Faces Application?

 

JavaServer Faces applications are just like any other Java web application. They run in a servlet container, and they typically contain the following:

 

  • JavaBeans components containing application-specific functionality and data.
  • Event listeners.
  • Pages, such as JSP pages.
  • Server-side helper classes, such as database access beans.

In addition to these items, a JavaServer Faces application also has:

 

  • A custom tag library for rendering UI components on a page.
  • A custom tag library for representing event handlers, validators, and other actions.
  • UI components represented as stateful objects on the server.
  • Backing beans, which define properties and functions for UI components.
  • Validators, converters, event listeners, and event handlers.
  • An application configuration resource file for configuring application resources.

What is Managed Bean?

 

JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the beans functionalities.

What is Backing Bean?

 

Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.

The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the components data, handling events that the component fires and performing processing associated with navigation when the component activates.

What is view object?

 

A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms.

How to reload the page after ValueChangeListener is invoked?

 

At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()method

What is the different between getRequestParameterMap() and getRequestParameterValuesMap()?

 

getRequestParameterValuesMap() method is similar to getRequestParameterMap(), but it returns multiple values for the parameters with the same name. This method is useful when using components such as &lt;h:selectMany&gt;

h:inputSecret field becomes empty when page is reloaded. How to fix this?

 

Set redisplay=true, it is false by default.

Explain JSF Architecture?

 

JSF was developed using MVC (a.k.a Model View Controller) design pattern so that applications
can be scaled better with greater maintainability. It is driven by Java Community Process (JCP) and has become a standard. The advantage of JSF is that its both a Java Web user a interface and a framework that fits well with the MVC. It provides clean separation between presentation and behavior. UI (a.k.a User Interface) can be created by page author using reusable UI components and business logic part can be implemented using managed beans.

What is required to start writing code in JSF?

 

Following things required for JSF:

 

  • JDK (Java SE Development Kit)
  • JSF jars
  • Application Server (Tomcat or any standard application server)
  • Integrated Development Environment (IDE) like Netbeans, Eclipse, etc.

Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding.

How to get current page URL from backing bean?

 

You can get a reference to the HTTP request object via FacesContext like this:
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

How to add context path to URL for outputLink?

 

Current JSF implementation does not add the context path for outputLink if the defined path starts with /. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:
&lt;h:outputLink value=”#{facesContext.externalContext.requestContextPath}/myPage.faces”&gt;

How to pass a parameter to the JSF application using the URL string?

 

If you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get(“id”);

EJB Interview Questions & Answers

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.

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)

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

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

How many types of MDB’s are there and what are they?

 

There are no different kinds of Message driven beans.

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.

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.

Explain the role of Home Interface.

 

Home interface contains factory methods for locating, creating and removing instances of EJB’s.

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.

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.

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.

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 tag.

What is meant by Activation?

 

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

What is meant by Passivation?

 

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

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.

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.

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.

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.

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.

What is a Primary Key?

 

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

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.

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.

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.

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.

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

 

Yes.

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.

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.

Explain about ACID properties of a transaction?

 

ACID is the acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, and durability.
Atomic : All or nothing. If a transaction is interrupted, all previous steps within that transaction are undone.
Consistent : The state of objects and/or the state of tables within a database move from one consistent state to another consistent state.
Isolated : What happens within one transaction should not affect or be visible within another transaction.
Durable : The effects of a transaction are persistent.

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.

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.

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

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.

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.

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.

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.

How many types of Isolation Level’s are available in EJB and what are they?

 

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.

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

 

Enterprise beans are restricted from invoking multithreading thread functionality.

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.

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.

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).

What is an EAR file?

 

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

What do mean by business method?

 

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

What is a finder method?

 

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

What is the difference between find and select methods in EJB?

 

A select method can return a persistent field (or a collection thereof) of a related entity bean. A finder method can return only a local or remote interface (or a collection of interfaces).

Because it is not exposed in any of the local or remote interfaces, a select method cannot be invoked by a client. It can be invoked only by the methods implemented within the entity bean class. A select method is usually invoked by either a business or a home method.

A select method is defined in the entity bean class. For bean-managed persistence, a finder method is defined in the entity bean class, but for container-managed persistence it is not.

Can I invoke Runtime.gc() in an EJB?

 

You shouldn’t. What will happen depends on the implementation, but the call will most likely be ignored.

What is the default transaction attribute in EJB?

 

The default transaction attribute of an EJB is

Quote:
SUPPORTS

.

Explain about setEntityContext method in Entity bean?

 

The setEntityContext() method is used to set the EntityContext interface for that bean. The EntityContext contains information about the context under which bean is operating. EntityContext interface gives security information about caller. The EntityContext is set only once in the life time of an entity bean instance.

What is the use of unsetEntityContext in Entity Bean?

 

The unsetEntityContext() method is called at the end of a beans life cycle before the instance is unloaded from memory. It is used to dereference EntityContext and to perform any clean up operations if required.

Explain ejbLoad and ejbStore methods of Entity Bean?

 

ejbLoad method is primarily used for data retrievals. ejbStore is used for updating data. Typically the container invokes ejbLoad before the first business method in a transaction and the ejbStore is invoked at the end of the transaction. ejbStore method will be invoked when any values of the entity are changed as part of the transaction.

When to use EJB?

 

The definition of EJB states that it is a distributed, transactional, persistent software component written in Java Programming Language. From this definition, it can be derived that EJBs are required in the following scenarios.

When the application is distributed: When the resources and data are distributed across multiple sites, then it is ideal to go for an application that is based on EJBs. Choose EJB when you know your application will need to scale beyond initial low usage levels and support multiple, concurrent users.

When the application is performance-centric, use of EJBs and the application server provide high performance and very good scalability.

Declaratively manage transactions. When transaction management is required to ensure data integrity, EJBs may be used. In EJB, you merely specify whether a beans methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you will have to write code to manage the transaction, which is difficult if a logical transaction must access multiple DataSources.

Declaratively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean.

Separation of Business Logic. The most significant difference between a web application using only servlets and one using servlets with EJBs is that the EJB model mandates a separation between display and business logic.

JMS Interview Questions & Answers

What is Messaging?

 

Messaging is a method of communication between software components or applications

What is JMS?

 

Java Message Service is a Java API that allows applications to create, send, receive, and read messages.

Is JMS a specification or a product?

 

JMS is a specification.

What are the features of JMS?

 

The following are the important features of JMS:

  • Asynchronous Processing.
  • Store and forwarding.
  • Guaranteed Delivery.
  • Provides location transparency.
  • Service based Architecture.

What are two messaging models or messaging domains?

 

The two messaging models are :

  • Point-to-Point Messaging domain.
  • Publish/Subscribe Messaging domain

Explain Point-to-Point Messaging model

 

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.
Point-to-Point Messaging has the following characteristics:

  • Each Message has only one consumer.
  • The receiver can fetch the message whether or not it was running when the client sent the message.
  • The receiver acknowledges the successful processing of a message.

Explain Pub/Sub Messaging model.

 

In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic’s multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.
Pub/sub messaging has the following characteristics:

  • Each message may have multiple consumers.
  • Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

What are the two types of Message Consumption?

 

  • Synchronous Consumption :A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.
  • Asynchronous Consumption : A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message.

What is a connection factory?

 

A connection factory is the object a client uses to create a connection with a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator.Each connection factory is an instance of either the QueueConnectionFactory or the TopicConnectionFactory interface.

What is a destination?

 

A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. In the PTP messaging domain, destinations are called queues and in the pub/sub messaging domain, destinations are called topics.

What is a message listener?

 

A message listener is an object that acts as an asynchronous event handler for messages. This object implements the MessageListener interface, which contains one method, onMessage. In the onMessage method, you define the actions to be taken when a message arrives.

What is a message selector?

 

Message selector filters the messages received by the consumer based on a criteria. Message selectors assign the work of filtering messages to the JMS provider rather than to the application. A message selector is a String that contains an expression. The syntax of the expression is based on a subset of the SQL92 conditional expression syntax. The message consumer then receives only messages whose headers and properties match the selector.

Can a message selector select messages on the basis of the content of the message body?

 

No. The message selection is only based on message header and message properties.

What are the parts of a JMS message?

 

A JMS message has three parts:

  • header
  • Properties (optional)
  • body (optional)

What is a message header?

 

A JMS message header contains a number of predefined fields that contain values that both clients and providers use to identify and to route messages.Each header field has associated setter and getter methods, which are documented in the description of the Message interface.

Name few message headers which are automatically assigned during message creation?

 

Following headers are automatically assigned:

  • JMSDestination
  • JMSDeliveryMode
  • JMSMessageID
  • JMSTimestamp
  • JMSExpiration
  • JMSRedelivered
  • JMSPriority

What are message properties?

 

Message properties are additional user defined properties other than those that are defined in the header.

What is the root exception of JMS?

 

JMSException is the root class for exceptions thrown by JMS API methods.

Name few subclasses of JMSException.

 

  • MessageFormatException
  • MessageEOFException
  • InvalidClientIDException
  • InvalidDestinationException
  • InvalidSelectorException

What is a Message?

 

A message is a package of business data that is sent from one application to another over the network. The message should be self-describing in that it should contain all the necessary context to allow the recipients to carry out their work independently.

How many types of Messages are there in JMS and What are they?

 

There are 5 types of Messages. They are:

  • TextMessage : A java.lang.String object (for example, the contents of an Extensible Markup Language file).
  • MapMessage : A set of name/value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.
  • BytesMessage : A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format.
  • StreamMessage: A stream of primitive values in the Java programming language, filled and read sequentially.
  • ObjectMessage: A Serializable object in the Java programming language.

What is a Topic?

 

A distribution mechanism for publishing messages that are delivered to multiple subscribers.

What is a Queue?

 

A staging area that contains messages that have been sent and are waiting to be read. Note that, contrary to what the name queue suggests, messages don’t have to be delivered in the order sent. If the message driven bean pool contains more than one instance then messages can be processed concurrently and thus it is possible that a later message is processed sooner than an earlier one. A JMS queue only guarantees that each message is processed only once.

Explain about JMS Client, Producer, Consumer, Provider.

 

Java applications that use JMS are called JMS clients, and the messaging system that handles routing and delivery of messages is called the JMS provider. A JMS client that sends a message is called a producer, while a JMS client that receives a message is called a consumer. A single JMS client can be both a producer and a consumer.

What is a Message Driven Bean?

 

Message-driven beans (MDBs) are stateless, server-side, transaction-aware components for processing asynchronous JMS messages. MDBs were introduced as part of EJB 2 specification. Message-driven beans process messages delivered via the Java Message Service.

A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component–an application client, another enterprise bean, or a Web component or by a JMS application or system that does not use J2EE technology.

Do MDBs have component interfaces?

 

MDBs do not have component interfaces ( ie remote or local interfaces).

Do MDB’s have JNDI?

 

No. MDB’s dont need component interfaces.

Why do MDB’s dont have component interfaces or JNDI?

 

MDB’s are only for internal processing. You cannot look up a MDB from client. If you want to access MDB you rather send a message to the Queue. Hence MDB’s doesnt have a JNDI name. And for the same reason they dont have component interfaces.

Can a single MDB be attached to different listeners in the same EAR?

How are MDBs different from Session and Entity Beans?

 

The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces. Unlike a session or entity bean, a message-driven bean has only a bean class.

What are similarities between MDB’s and Stateless Session Bean?

 

In several respects, a message-driven bean resembles a stateless session bean.

  • A message-driven bean’s instances retain no data or conversational state for a specific client.
  • All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.
  • A single message-driven bean can process messages from multiple clients.

What are the two parts of a message and explain them?

 

A message basically has two parts : a header and payload. The header is comprised of special fields that are used to identify the message, declare attributes of the message, and provide information for routing. Payload is the type of application data the message contains.

What are the two types of delivery modes?

 

JMS delivery mode are of two types Non-Persistent and Persistent.
Non-Persistent messages do not need to be stored in persistent storage in case of client failure. A JMS provider must deliver this kind of message at-most-once, i.e., the message can be lost, but can only be delivered once.
Persistent messages are stored in persistent storage to be delivered at a later date if a client is unavailable. A JMS provider must deliver this kind of message once-and-only once, i.e., it cannot be lost and cannot be delivered more than once.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *