Collectiion of Java and J2EE Questions

download Collectiion of Java and J2EE Questions

of 35

Transcript of Collectiion of Java and J2EE Questions

  • 8/6/2019 Collectiion of Java and J2EE Questions

    1/35

    V.Parthipan AP/CSE [email protected]

    OOPS INTERVIEW QUESTIONS AND ANSWERS

    1) What is meant by Object Oriented Programming?OOP is a method of programming in which programs are organised as cooperative

    collections of objects. Each object is an instance of a class and each class belong to ahierarchy.

    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 similarclasses are defined in their common class. An instance is also called as an object.

    5) What are the core OOP's concepts?Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP's

    concepts.

    6) What is meant by abstraction?Abstraction defines the essential characteristics of an object that distinguish it from all

    other kinds of objects. Abstraction provides crisply-defined conceptual boundariesrelative to the perspective of the viewer. Its the process of focussing on the essentialcharacteristics 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 contractualinterface 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 sharesthe structure or behaviour from multiple classes, then it is called Multiple Inheritance.Inheritance defines "is-a" hierarchy among classes in which one subclass inherits fromone 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, tosomething 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

    1

  • 8/6/2019 Collectiion of Java and J2EE Questions

    2/35

    V.Parthipan AP/CSE [email protected]

    expectation that its concrete subclasses will add to its structure and behaviour, typicallyby 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 andtime.

    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.

    2

  • 8/6/2019 Collectiion of Java and J2EE Questions

    3/35

    V.Parthipan AP/CSE [email protected]

    24) How is polymorphism acheived in java?Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.

    JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS

    1) Which package contains exception handling related classes?java.lang

    2) What are the two types of Exceptions?Checked Exceptions and Unchecked Exceptions.

    3) What is the base class of all exceptions?java.lang.Throwable

    4) What is the difference between Exception and Error in java?Exception and Error are the subclasses of the Throwable class. Exception class isused for exceptional conditions that user program should catch. Error defines exceptionsthat are not excepted to be caught by the user program. Example is Stack Overflow.

    5) 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 nothandled by the method. It must specify this behavior so the callers of the method canguard against the exceptions. throws is specified in the method signature. If multipleexceptions are not handled, then they are separated by a comma. the statement wouldbe as follows: public void doSomething() throws IOException,MyException{}

    6) 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 explicitlyhandled. RuntimeException and it's subclasses, Error and it's subclasses fall underunchecked exceptions.

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

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

    9) Can a catch block exist without a try block?

    3

  • 8/6/2019 Collectiion of Java and J2EE Questions

    4/35

    V.Parthipan AP/CSE [email protected]

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

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

    11) What will happen to the Exception object after exception handling?Exception object will be garbage collected.

    12) The subclass exception should precede the base class exception when usedwithin the catch clause. True/False?

    True.

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

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

    15) 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 bythe JVM just before an object is garbage collected.

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

    4

  • 8/6/2019 Collectiion of Java and J2EE Questions

    5/35

    V.Parthipan AP/CSE [email protected]

    JAVA THREADS INTERVIEW QUESTIONS AND ANSWERS

    1) What are the two types of multitasking ?a. Process-based.

    b. Thread-based.

    2) What is a Thread ?A thread is a single sequential flow of control within a program.

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

    4) If you have ABC class that must subclass XYZ class, which option will you useto create a thread?

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

    5) Which package contains Thread class and Runnable Interface? java.lang package

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

    7) Which methods calls the run() method?start() method.

    8) Which interface does the Thread class implement?Runnable interface

    9) What are the states of a Thread ?Ready,Running,Waiting and Dead.

    10) Where does the support for threading lie?The thread support lies in java.lang.Thread, java.lang.Object and JVM.

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

    5

  • 8/6/2019 Collectiion of Java and J2EE Questions

    6/35

    V.Parthipan AP/CSE [email protected]

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

    13) What will notify() method do?

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

    14) Can you notify a particular thread?No.

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

    16) What is a Daemon Thread?Daemon is a low priority thread which runs in the backgrouund.

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

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

    19) Give one good example of a daemon thread?Garbage Collector is a low priority daemon thread.

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

    21) What are the two ways that a code can be synchronised?a. Method can be declared as synchronised.

    b. A block of code be sychronised.

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

    23) Can a thread execute another objects run() method?A thread can execute it's own run() method or another objects run() method.

    24) What is the default priority of a Thread?NORM_PRIORITY

    25) What is a deadlock?A condition that occurs when two processes are waiting for each other to complete

    6

  • 8/6/2019 Collectiion of Java and J2EE Questions

    7/35

    V.Parthipan AP/CSE [email protected]

    before proceeding. The result is that both processes wait endlessly.

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

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

    27) What is the mechanisam defind in java for a code segment be used by onlyone Thread at a time?

    Synchronisation

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

    29) What is the unit for 500 in the statement, obj.sleep(500);?500 is the no of milliseconds and the data type is long.

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

    10,1,5

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

    32) The word synchronized can be used with only a method. True/ False?False. A block of code can also be synchronised.

    33) What is a Monitor?A monitor is an object which contains some synchronized code in it.

    34) What are all the methods defined in the Runnable Interface?only run() method is defined the Runnable interface.

    35) How can i start a dead thread?A dead Thread cannot be started again.

    36) When does a Thread die?A Thread dies after completion of run() method.

    37) What does the yield() method do?The yield() method puts currently running thread in to ready state.

    38) What exception does the wait() method throw?The java.lang.Object class wait() method throws "InterruptedException".

    39) What does notifyAll() method do?notifyAll() method moves all waiting threads from the waiting pool to ready state.

    7

  • 8/6/2019 Collectiion of Java and J2EE Questions

    8/35

    V.Parthipan AP/CSE [email protected]

    40) What does wait() method do?wait() method releases CPU, releases objects lock, the thread enters into pool of

    waiting threads.

    JAVA GARBAGE COLLECTION INTERVIEW QUESTIONS AND ANSWERS

    1) Explain Garbage collection in Java?In Java, Garbage Collection is automatic. Garbage Collector Thread runs as a lowpriority daemon thread freeing memory.

    2) When does the Garbage Collection happen?When there is not enough memory. Or when the daemon GC thread gets a chance torun.

    3) When is an Object eligible for Garbage collection?

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

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

    5) What is the purpose of finalization?The purpose of finalization is to give an unreachable object the opportunity to performany cleanup processing before the object is garbage collected.

    6) Can GC be forced in Java?No. GC can't be forced.

    7) 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 isup to the JVM to run GC immediately or run it when it gets time.

    8) When is the finalize() called?finalize() method is called by the GC just before releasing the object's memory. It isnormally advised to release resources held by the object in finalize() method.

    8

  • 8/6/2019 Collectiion of Java and J2EE Questions

    9/35

    V.Parthipan AP/CSE [email protected]

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

    10) 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 becleared till the JVM cease to exist.

    11) GC is single threaded or multi threaded?Garbage Collection is multi threaded from JDK1.3 onwards.

    12) What are the good programming practices for better memory management?a. We shouldn't declare unwanted variables and objects.b. We should avoid declaring variables or instantiating objects inside loops.c. When an object is not required, its reference should be nullified.d. We should minimize the usage of String object and SOP's.

    13) When is the Exception object in the Exception block eligible for GC?Immediately after Exception block is executed.

    14) When are the local variables eligible for GC?Immediately after method's execution is completed.

    15) If an object reference is set to null, Will GC immediately free the memory heldby that object?No. It will be garbage collected only in the next GC cycle.

    JAVA COLLECTIONS INTERVIEW QUESTIONS AND ANSWERS

    1) Explain Java Collections Framework?Java Collections Framework provides a well designed set of interfaces and classesthat support operations on a collections of objects.

    2) Explain Iterator Interface.An Iterator is similar to the Enumeration interface.With the Iterator interface methods,

    you can traverse a collection from start to end and safely remove elements from theunderlying Collection. The iterator() method generally used in query operations.Basic methods:iterator.remove();iterator.hasNext();iterator.next();

    3) Explain Enumeration Interface.The Enumeration interface allows you to iterate through all the elements of a

    collection. Iterating through an Enumeration is similar to iterating through an Iterator.However, there is no removal support with Enumeration.Basic methods:boolean hasMoreElements();Object nextElement();

    9

  • 8/6/2019 Collectiion of Java and J2EE Questions

    10/35

    V.Parthipan AP/CSE [email protected]

    4) What is the difference between Enumeration and Iterator interface?The Enumeration interface allows you to iterate through all the elements of a

    collection. Iterating through an Enumeration is similar to iterating through an Iterator.However, there is no removal support with Enumeration.

    5) Explain Set Interface.In mathematical concept, a set is just a group of unique items, in the sense that the

    group contains no duplicates. The Set interface extends the Collection interface. Setdoes not allow duplicates in the collection. In Set implementations null is valid entry, butallowed only once.

    6) What are the two types of Set implementations available in the CollectionsFramework?

    HashSet and TreeSet are the two Set implementations available in the CollectionsFramework.

    7) What is the difference between HashSet and TreeSet?HashSet Class implements java.util.Set interface to eliminate the duplicate entries

    and uses hashing for storage. Hashing is nothing but mapping between a key value anda data item, this provides efficient searching.

    The TreeSet Class implements java.util.Set interface provides an ordered set, eliminatesduplicate entries and uses tree for storage.

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

    the Collection interface.

    9) What are the two types of List implementations available in the CollectionsFramework?

    ArrayList and LinkedList are the two List implementations available in the CollectionsFramework.

    10) What is the difference between ArrayList and LinkedList?The ArrayList Class implements java.util.List interface and uses array for storage. An

    array storage's are generally faster but we cannot insert and delete entries in middle ofthe 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.Alinked list allow elements to be added, removed from the collection at any location in thecontainer by ordering the elements.With this implementation you can only access theelements in sequentially.

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

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

    10

  • 8/6/2019 Collectiion of Java and J2EE Questions

    11/35

    V.Parthipan AP/CSE [email protected]

    13) Explain Map Interface.A map is a special kind of set with no duplicates.The key values are used to lookup,

    or index the stored data. The Map interface is not an extension of Collection interface, it

    has it's own hierarchy. Map does not allow duplicates in the collection. In Mapimplementations null is valid entry, but allowed only once.

    14) What are the two types of Map implementations available in the CollectionsFramework?

    HashMap and TreeMap are two types of Map implementations available in theCollections Framework.

    15) What is the difference between HashMap and TreeMap?The HashMap Class implements java.util.Map interface and uses hashing for

    storage. Indirectly Map uses Set functionality so, it does not permit duplicates. TheTreeMap Class implements java.util.Map interface and uses tree for storage. It providesthe ordered map.

    16) Explain the functionality of Vector Class?Once array size is set you cannot change size of the array. To deal with this kind of

    situations in Java uses Vector, it grows and shrink it's size automatically. Vector allowsto store only objects not primitives. To store primitives, convert primitives in to objectsusing wrapper classes before adding them into Vector.The Vector reallocates andresizes itself automatically.

    17) What does the following statement convey?Vector vt = new Vector(3, 10);

    vt is an instance of Vector class with an initial capacity of 3 and grows in increment of10 in each relocation

    18) How do you store a primitive data type within a Vector or other collectionsclass?

    You need to wrap the primitive data type into one of the wrapper classes found in thejava.lang package, like Integer, Float, or Double, as in:Integer in = new Integer(5);

    19) What is the difference between Vector and ArrayList?Vector and ArrayList are very similar. Both of them represent a growable array. The

    main difference is that Vector is synchronized while ArrayList is not.

    20) What is the between Hashtable and HashMap?Both provide key-value access to data. The key differences are :

    a. Hashtable is synchronised but HasMap is not synchronised.b. HashMap permits null values but Hashtable doent allow null values.c. iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not failsafe.

    11

  • 8/6/2019 Collectiion of Java and J2EE Questions

    12/35

    V.Parthipan AP/CSE [email protected]

    21) How do I make an array larger?You cannot directly make an array larger. You must make a new (larger) array and

    copy the original elements into it, usually with System.arraycopy(). If you find yourselffrequently doing this, the Vector class does this automatically for you, as long as your

    arrays are not of primitive data types.

    22) Which is faster, synchronizing a HashMap or using a Hashtable for thread-safeaccess?

    Because a synchronized HashMap requires an extra method call, a Hashtable isfaster for synchronized access.

    23) In which package would you find the interfaces amd claases defined in theJava Collection Framework?

    java.util

    24) What method in the System class allows you to copy eleemnts from one arrayto another?

    System. arraycopy()

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

    ArrayIndexOutofBoundsException

    26) What is the use of Locale class?The Locale class is used to tailor program output to the conventions of a particular

    geographic, political, or cultural region27) What is the use of GregorianCalendar class?

    The GregorianCalendar provides support for traditional Western calendars

    28) What is the use of SimpleTimeZone class?The SimpleTimeZone class provides support for a Gregorian calendar

    29) What is the use of ResourceBundle class?The ResourceBundle class is used to store locale-specific resources that can be

    loaded by a program to tailor the program's appearance to the particular locale in whichit is being run

    JAVA.LANG PACKAGE

    1) What is the base class of all classes?java.lang.Object

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

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

    12

  • 8/6/2019 Collectiion of Java and J2EE Questions

    13/35

    V.Parthipan AP/CSE [email protected]

    Basically for interthread communication.

    4) What is the importance of == and equals() method with respect to Stringobject?

    == 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 contentwill refer to the same object.

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

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

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

    str1.equals(str2) will be true.str1==str2 will be false.

    5) Is String a Wrapper Class or not?No. String is not a Wrapper class.

    6) How will you find length of a String object?Using length() method of String class.

    7) How many objects are in the memory after the exection of following codesegment?String str1 = "ABC";String str2 = "XYZ";String str1 = str1 + str2;There are 3 Objects.

    8) What is the difference between an object and object reference?An object is an instance of a class. Object reference is a pointer to the object. Therecan be many refernces to the same object.

    9) What will trim() method of String class do?trim() eliminate spaces from both the ends of a string.***

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

    12) What is the difference between String and Stringbuffer?

    13

  • 8/6/2019 Collectiion of Java and J2EE Questions

    14/35

    V.Parthipan AP/CSE [email protected]

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

    13) What is the use of Math class?

    Math class provide methods for mathametical functions.

    14) Can you instantiate Math class?No. It cannot be instantited. The class is final and its constructor is private. But all themethods are static, so we can use them without instantiating the Math class.

    15) What will Math.abs() do?It simply returns the absolute value of the value supplied to the method, i.e. givesyou the same value. If you supply negative value it simply removes the sign.

    16) What will Math.ceil() do?This method returns always double, which is not less than the supplied value. Itreturns next available whole number

    17) What will Math.floor() do?This method returns always double, which is not greater than the supplied value.

    18) What will Math.max() do?The max() method returns greater value out of the supplied values.

    19) What will Math.min() do?The min() method returns smaller value out of the supplied values.

    20) What will Math.random() do?The random() method returns random number between 0.0 and 1.0. It always returnsdouble.

    JMS INTERVIEW QUESTIONS AND ANSWERS

    1) What is Messaging?Messaging is a method of communication between software components orapplications

    2) What is JMS?Java Message Service is a Java API that allows applications to create, send,receive, and read messages.

    3) Is JMS a specification or a product?JMS is a specification.

    4) What are the features of JMS?The following are the important features of JMS:a. Asynchronous Processing.b. Store and forwarding.c. Guaranteed delivery.

    14

  • 8/6/2019 Collectiion of Java and J2EE Questions

    15/35

    V.Parthipan AP/CSE [email protected]

    d. Provides location transparency.e. Service based Architecture.

    5) What are two messaging models or messaging domains?

    a. Point-to-Point Messaging domain.b. Publish/Subscribe Messaging domain

    6) Explain Point-to-Point Messaging model.A point-to-point (PTP) product or application is built around the concept ofmessage queues, senders, and receivers. Each message is addressed to aspecific queue, and receiving clients extract messages from the queue(s)established to hold their messages. Queues retain all messages sent to themuntil the messages are consumed or until the messages expire.Point-to-Point Messaging has the following characteristics:a. Each Message has only one consumer.b. The receiver can fetch the message whether or not it was running when theclient sent the message.c. The receiver acknowledges the successful processing of a message.

    7) Explain Pub/Sub Messaging model.In a publish/subscribe (pub/sub) product or application, clients addressmessages to a topic. Publishers and subscribers are generally anonymous andmay dynamically publish or subscribe to the content hierarchy. The system takescare of distributing the messages arriving from a topic's multiple publishers to itsmultiple subscribers. Topics retain messages only as long as it takes to distributethem to current subscribers.Pub/sub messaging has the following characteristics:a. Each message may have multiple consumers.b. Publishers and subscribers have a timing dependency. A client that subscribesto a topic can consume only messages published after the client has created asubscription, and the subscriber must continue to be active in order for it toconsume messages.

    8) What are the two types of Message Consumption?a. Synchronous Consumption :A subscriber or a receiver explicitly fetches themessage from the destination by calling the receive method. The receive methodcan block until a message arrives or can time out if a message does not arrivewithin a specified time limit.

    b. Asynchronous Consumption : A client can register a message listener with aconsumer. A message listener is similar to an event listener. Whenever amessage arrives at the destination, the JMS provider delivers the message bycalling the listener's onMessage method, which acts on the contents of themessage.

    9) What is a connection factory?A connection factory is the object a client uses to create a connection with aprovider. A connection factory encapsulates a set of connection configuration

    15

  • 8/6/2019 Collectiion of Java and J2EE Questions

    16/35

    V.Parthipan AP/CSE [email protected]

    parameters that has been defined by an administrator.Each connection factory isan instance of either the QueueConnectionFactory or theTopicConnectionFactory interface.

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

    11) What is a message listener?A message listener is an object that acts as an asynchronous event handler formessages. This object implements the MessageListener interface, whichcontains one method, onMessage. In the onMessage method, you define theactions to be taken when a message arrives.

    12) What is a message selector?Message selector filters the messages received by the consumer based on acriteria. Message selectors assign the work of filtering messages to the JMSprovider rather than to the application. A message selector is a String thatcontains an expression. The syntax of the expression is based on a subset of theSQL92 conditional expression syntax. The message consumer then receivesonly messages whose headers and properties match the selector.

    13) Can a message selector select messages on the basis of the content ofthe message body?No. The message selection is only based on message header and messageproperties.

    14) What are the parts of a JMS message?A JMS message has three parts:a. headerb. Properties (optional)c. body (optional)

    15) What is a message header?A JMS message header contains a number of predefined fields that containvalues that both clients and providers use to identify and to route messages.Eachheader field has associated setter and getter methods, which are documented inthe description of the Message interface.

    16) What are message properties?Message properties are additional user defined properties other than those thatare defined in the header.

    17) What is the root exception of JMS?JMSException is the root class for exceptions thrown by JMS API methods.

    18) Name few subclasses of JMSException.

    16

  • 8/6/2019 Collectiion of Java and J2EE Questions

    17/35

    V.Parthipan AP/CSE [email protected]

    a. MessageFormatExceptionb. MessageEOFExceptionc. InvalidClientIDExceptiond. InvalidDestinationException

    e. InvalidSelectorException

    19) What is a Message?A message is a package of business data that is sent from one application toanother over the network. The message should be self-describing in that itshould contain all the necessary context to allow the recipients to carry out theirwork independently.

    20) How many types are there and What are they?There are 5 types of Messages. They are:a. TextMessage : A java.lang.String object (for example, the contents of anExtensible Markup Language file).b. MapMessage : A set of name/value pairs, with names as String objects andvalues as primitive types in the Java programming language. The entries can beaccessed sequentially by enumerator or randomly by name. The order of theentries is undefined.c. BytesMessage : A stream of uninterpreted bytes. This message type is forliterally encoding a body to match an existing message format.d. StreamMessage: A stream of primitive values in the Java programminglanguage, filled and read sequentially.e. ObjectMessage: A Serializable object in the Java programming language.

    21) What are the two parts of a message and explain them?A message basically has two parts : a header and payload. The header iscomprised of special fields that are used to identify the message, declareattributes of the message, and provide information for routing. Payload is thetype of application data the message contains.

    RMI INTERVIEW QUESTIONS AND ANSWERS

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

    2) What is the basic principle of RMI architecture?The RMI architecture is based on one important principle: the definition of behavior andthe implementation of that behavior are separate concepts. RMI allows the code thatdefines the behavior and the code that implements the behavior to remain separate and

    17

  • 8/6/2019 Collectiion of Java and J2EE Questions

    18/35

    V.Parthipan AP/CSE [email protected]

    to run on separate JVMs.

    3) What are the layers of RMI Architecture?The RMI is built on three layers.

    a. Stub and Skeleton layerThis layer lies just beneath the view of the developer. This layer intercepts method callsmade by the client to the interface reference variable and redirects these calls to aremote RMI service.

    b. Remote Reference Layer.This layer understands how to interpret and manage references made from clients to theremote service objects. The connection is a one-to-one (unicast) link.

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

    4) What is the role of Remote Interface in RMI?The Remote interface serves to identify interfaces whose methods may be invoked froma non-local virtual machine. Any object that is a remote object must directly or indirectlyimplement this interface. Methods that are to be invoked remotely must be identified inRemote Interface. All Remote methods should throw RemoteException.

    5) What is the role java.rmi.Naming Class?The Naming class provides methods for storing and obtaining references to remoteobjects in the remote object registry.

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

    7) What is meant by binding in RMI?Binding is a process of associating or registering a name for a remote object that can beused at a later time to look up that remote object. A remote object can be associatedwith a name using the Naming class's bind or rebind methods.

    8) What is the difference between using bind() and rebind() methods of NamingClass?bind method(String name) binds the specified name to a remote object whilerebind(String name) method rebinds the specified name to a new remote object,anyexisting binding for the name is replaced.

    9) When is AlreadyBoundException thrown and by which method?AlreadyBoundException is thrown by bind(String name) method when a remote object isalready registered with the registry with the same name.Note: rebind method doesn't throw AlreadyBoundException because it replaces theexisting binding with same name.

    10) How to get all the registered objects in a rmiregistry?Using list method of Naming Class.

    18

  • 8/6/2019 Collectiion of Java and J2EE Questions

    19/35

    V.Parthipan AP/CSE [email protected]

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

    22) What is the protocol used by RMI?JRMP(java remote method protocol)

    23) What is the use of UnicastRemoteObject in RMI?The UnicastRemoteObject class provides support for point-to-point active objectreferences using TCP streams. Objects that require remote behavior should extendUnicastRemoteObject.

    24) What does the exportObject of UnicastRemoteObject do?Exports the remote object to make it available to receive incoming calls, using theparticular supplied port. If port not specified receives calls from any anonymous port.

    25) What is PortableRemoteObject.narrow() method and what is used for?Java RMI-IIOP provides a mechanism to narrow the the Object you have received fromfrom your lookup, to the appropriate type. This is done through the

    javax.rmi.PortableRemoteObject class and, more specifically, using the narrow()method.

    26) In a RMI Client Program, what are the excpetions which might have tohandled?a. MalFormedURLExceptionb. NotBoundExceptionc. RemoteException

    JDBC question on Jguide.org

    1) 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 toconcern yourself with the underlying details of a particular database.

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

    19

  • 8/6/2019 Collectiion of Java and J2EE Questions

    20/35

    V.Parthipan AP/CSE [email protected]

    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 Netpure Java Driver

    3) Explain the role of Driver in JDBC?The JDBC Driver provides vendor-specific implementations of the abstractclasses provided by the JDBC API. Each vendors driver must provideimplementations of the java.sql.Connection,Statement,PreparedStatement,CallableStatement, ResultSet and Driver.

    4) Is java.sql.Driver a class or an Interface ?It's an interface.5) Is java.sql.DriverManager a class or an Interface ?It's a class. This class provides the static getConnection method, through whichthe database connection is obtained.

    6) Is java.sql.Connection a class or an Interface ?java.sql.Connection is an interface. The implmentation is provided by the vendorspecific Driver.

    7) Is java.sql.Statement a class or an Interface ? java.sql.Statement,java.sql.PreparedStatement and java.sql.CallableStatementare interfaces.

    8) Which interface do PreparedStatement extend?java.sql.Statement

    9) Which interface do CallableStatement extend?CallableStatement extends PreparedStatement.

    10) What is the purpose Class.forName("") method?The Class.forName("") method is used to load the driver.11) Do you mean that Class.forName("") method can only be used to load adriver?The Class.forName("") method can be used to load any class, not just thedatabase vendor driver class.

    12) Which statement throws ClassNotFoundException in SQL code block?and why?Class.forName("") method throws ClassNotFoundException. This exception isthrown when the JVM is not able to find the class in the classpath.

    13) What exception does Class.forName() throw?ClassNotFoundException.14) What is the return type of Class.forName() method ?

    java.lang.Class

    15) Can an Interface be instantiated? If not, justify and explain the followingline of code:

    20

  • 8/6/2019 Collectiion of Java and J2EE Questions

    21/35

    V.Parthipan AP/CSE [email protected]

    Connection con = DriverManager.getConnection("dsd","sds","adsd");An interface cannot be instantiated. But reference can be made to a interface.When a reference is made to interface, the refered object should haveimplemented all the abstract methods of the interface. In the above mentioned

    line, DriverManager.getConnection method returns Connection Object withimplementation for all abstract methods.

    16) What type of a method is getConnection()?static method.

    17) What is the return type for getConnection() method?Connection object.

    18) What is the return type for executeQuery() method?ResultSet

    19) What is the return type for executeUpdate() method and what does thereturn type indicate?int. It indicates the no of records affected by the query.

    20) What is the return type for execute() method and what does the returntype indicate?boolean. It indicates whether the query executed sucessfully or not.21) is Resultset a Classor an interface?Resultset is an interface.

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

    23) What is the use of CallableStatement?CallableStatement is used to execute Stored Procedures.

    24) Name the method, which is used to prepare CallableStatement?CallableStament.prepareCall().

    25) What do mean by Connection pooling?Opening and closing of database connections is a costly excercise. So a pool ofdatabase connections is obtained at start up by the application server andmaintained in a pool. When there is a request for a connection from theapplication, the application server gives the connection from the pool and whenclosed by the application is returned back to the pool. Min and max size of theconnection pool is configurable. This technique provides better handling ofdatabase connectivity.

    SERVLETS INTERVIEW QUESTIONS AND ANSWERS

    21

  • 8/6/2019 Collectiion of Java and J2EE Questions

    22/35

    V.Parthipan AP/CSE [email protected]

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

    2) Explain the architechture of a Servlet?javax.servlet.Servlet interface is the core abstraction which has to be implemented by allservlets either directly or indirectly. Servlet run on a server side JVM ie the servletcontainer.Most servlets implement the interface by extending either

    javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet.A single servlet objectserves multiple requests using multithreading.

    3) What is the difference between an Applet and a Servlet?An Applet is a client side java program that runs within a Web browser on the clientmachine whereas a servlet is a server side component which runs on the web server. Anapplet can use the user interface classes like AWT or Swing while the servlet does nothave a user interface. Servlet waits for client's HTTP requests from a browser andgenerates a response that is displayed in the browser.

    4) What is the difference between GenericServlet and HttpServlet?GenericServlet is a generalised and protocol independent servlet which defined in

    javax.servlet package. Servlets extending GenericServlet should override service()method. javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is httpprotocol specific ie it services only those requests thats coming through http.A subclassof HttpServlet must override at least one method of doGet(), doPost(),doPut(),doDelete(), init(), destroy() or getServletInfo().

    5) Explain life cycle of a Servlet?On client's initial request, Servlet Engine loads the servlet and invokes the init() methodsto initialize the servlet. The servlet object then handles subsequent client requests byinvoking the service() method. The server removes the servlet by calling destry()method.

    6) What is the difference between doGet() and doPost()?doGET Method : Using get method we can able to pass 2K data from HTML All data weare passing to Server will be displayed in URL (request string).

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

    7) What is the difference between ServletConfig and ServletContext?ServletConfig is a servlet configuration object used by a servlet container to passinformation to a servlet during initialization. All of its initialization parameters can only beset in deployment descriptor. The ServletConfig parameters are specified for a particularservlet and are unknown to other servlets.The ServletContext object is contained withinthe ServletConfig object, which the Web server provides the servlet when the servlet isinitialized. ServletContext is an interface which defines a set of methods which theservlet uses to interact with its servlet container. ServletContext is common to allservlets within the same web application. Hence, servlets use ServletContext to sharecontext information.

    22

  • 8/6/2019 Collectiion of Java and J2EE Questions

    23/35

    V.Parthipan AP/CSE [email protected]

    8) What is the difference between using getSession(true) and getSession(false)methods?getSession(true) method will check whether already a session is existing for the user. Ifa session is existing, it will return the same session object, Otherwise it will create a new

    session object and return taht object.

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

    9) What is meant by a Web Application?A Web Application is a collection of servlets and content installed under a specific subsetof the server's URL namespace such as /catalog and possibly installed via a .war file.

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

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

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

    13) What is the structure of the HTTP response?The response can have 3 parts:1) Status Code - describes the status of the response. For example, it could indicate thatthe request was successful, or that the request failed because the resource was notavailable. 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, theheader could specify the method used to compress the response body.3) Body - contents of the response. The body could contain HTML code, an image, etc.

    14) What is a cookie?A cookie is a bit of information that the Web server sends to the browser which thensaves the cookie to a file. The browser sends the cookie back to the same server inevery request that it makes. Cookies are often used to keep track of sessions.

    15) Which code line must be set before any of the lines that use the PrintWriter?setContentType() method must be set.

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

    23

  • 8/6/2019 Collectiion of Java and J2EE Questions

    24/35

    V.Parthipan AP/CSE [email protected]

    17) Can we use the constructor, instead of init(), to initialize servlet?Yes, of course you can use the constructor instead of init(). There's nothing to stop you.But you shouldn't. The original reason for init() was that ancient versions of Java couldn'tdynamically invoke constructors with arguments, so there was no way to give the

    constructur a ServletConfig. That no longer applies, but servlet containers still will onlycall your no-arg constructor. So you won't have access to a ServletConfig orServletContext.

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

    19) What is the Max amount of information that can be saved in a Session Object?As such there is no limit on the amount of information that can be saved in a SessionObject. Only the RAM available on the server machine is the limitation. The only limit isthe Session ID length(Identifier) , which should not exceed more than 4K. If the data tobe 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 Sessionexceeds the predefined limit, most of the servers write it to a temporary cache on harddisk.

    20) What is HTTP Tunneling?HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPSprotocols. Normally the intra-network of an organization is blocked by a firewall and thenetwork is exposed to the outer world only through a specific web server port , thatlistens 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 otherprotocol requests as http requests is HTTP Tunneling.

    21) What's the difference between sendRedirect( ) and forward( ) methods?A sendRedirect method creates a new request (it's also reflected in browser's URL )where as forward method forwards the same request to the new target(hence thechange is NOT reflected in browser's URL). The previous request scope objects are nolonger available after a redirect because it results in a new request, but it's available inforward. sendRedirect is slower compared to forward.

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

    23) Is it true that servlet containers service each request by creating a newthread? If that is true, how does a container handle a sudden dramatic surge inincoming requests without significant performance degradation?The implementation depends on the Servlet engine. For each request generally, a newThread is created. But to give performance boost, most containers, create and maintaina thread pool at the server startup time. To service a request, they simply borrow a

    24

  • 8/6/2019 Collectiion of Java and J2EE Questions

    25/35

    V.Parthipan AP/CSE [email protected]

    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 resourceexhaustion problem associated with unlimited thread allocation. The lower bound caninstruct the pool not to keep too many idle threads, freeing them if needed.

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

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

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

    28) How to determine the client browser version?Another name for "browser" is "user agent." You can read the User-Agent header usingrequest.getUserAgent() or request.getHeader("User-Agent")

    25

  • 8/6/2019 Collectiion of Java and J2EE Questions

    26/35

  • 8/6/2019 Collectiion of Java and J2EE Questions

    27/35

    V.Parthipan AP/CSE [email protected]

    component level without editing the individual pages that use the logic.

    6) How is a JSP page invoked and compiled?Pages built using JSP technology are typically implemented using a translation phase

    that is performed once, the first time the page is called. The page is compiled into a JavaServlet class and remains in server memory, so subsequent calls to the page have veryfast response times.

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

    8) What are the different types of directives available in JSP?Ans : The following are the different types of directives:a. include directive : used to include a file and merges the content of the file with thecurrent pageb. page directive : used to define page specific attributes like scripting language, errorpage, buffer, thread safety, etcc. taglib : used to declare a custom tag library which is used in the page.

    9) What are JSP actions?JSP actions are executed when a JSP page is requested. Action are inserted in the jsppage using XML syntax to control the behavior of the servlet engine. Using action, wecan 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: - include a file at the time the page is requested. - find or instantiate a JavaBean. - set the property of a JavaBean. - insert the property of a JavaBean into the output. - forward the requester to a new page. - generate browser-specific code that makes an OBJECT or EMBED tag forthe Java plugin.

    10) What are Scriptlets?Scriptlets are blocks of programming language code (usually java) embedded within aJSP page. Scriptlet code is inserted into the servlet generated from the page. Scriptletcode is defined between

    11) What are Decalarations?Declarations are similar to variable declarations in Java.Variables are defined forsubsequent use in expressions or scriptlets. Declarations are defined between .< %! int i=0; %>

    27

  • 8/6/2019 Collectiion of Java and J2EE Questions

    28/35

    V.Parthipan AP/CSE [email protected]

    12) How to declare instance or global variables in jsp?Instance variables should be declared inside the declaration part. The variables declaredwith JSP declaration element will be shared by all requests to the jsp page.< %@ page language=="java" contentType="text/html"% >

    < %! int i=0; %>

    13) What are Expressions?Expressions are variables or constants that are inserted into the data returned by theweb server. Expressions are defined between < %= scorer.getScore() %>

    14) What is meant by implicit objects? And what are they?Ans : Implicit objects are those objects which are avaiable by default. These objects areinstances of classesdefined by the JSP specification. These objects could be used withinthe jsp page without being declared.

    The following are the implicit jsp objects:1. application2. page3. request4. response5. session6. exception7. out8. config9. pageContext

    15) How do I use JavaBeans components (beans) from a JSP page?The JSP specification includes standard tags for bean use and manipulation. The tag creates an instance of a specific JavaBean class. If the instancealready exists, it is retrieved. Otherwise, a new instance of the bean is created. The and tags let you manipulate properties of a specificbean.

    16) What is the difference between and Both are used to insert files into a JSP page. is a directive which statically inserts the file at the time the JSP page istranslated into a servlet. is an action which dynamically inserts the file at the time the page isrequested.

    17) What is the difference between forward and sendRedirect?Both requestDispatcher.forward() and response.sendRedirect() is used to redirect tonew url.

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

    28

  • 8/6/2019 Collectiion of Java and J2EE Questions

    29/35

    V.Parthipan AP/CSE [email protected]

    sendRedirect is normally an external redirection of user request outside the webcontainer. 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 isslower than forward because it involves extra server call.

    18) Can I create XML pages using JSP technology?Yes, the JSP specification does support creation of XML documents. For simple XMLgeneration, 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 thatgenerate XML output.

    19) How is Java Server Pages different from Active Server Pages?JSP is a community driven specification whereas ASP is a similar proprietary technologyfrom 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 Webservers whereas it is not possible with ASP

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

    29

  • 8/6/2019 Collectiion of Java and J2EE Questions

    30/35

    V.Parthipan AP/CSE [email protected]

    EJB INTERVIEW QUESTIONS AND ANSWERS

    1) What are Enterprise Java Beans?Enterprise Java Beans (EJB) is a specification which defines a component architecture

    for developing distributed systems. Applications written using the Enterprise JavaBeansarchitecture are resusable,scalable, transactional, and secure. Enterprise Java Bean'sallow the developer to only focus on implementing the business logic of the application.

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

    4) How many types of Entity beans are there and what are they?There are 2 types Entity bean's and they are:

    1. Container Managed Persistence(CMP) Entity Bean's2. Bean Managed Persistence(BMP) Entity Bean's

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

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

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

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

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

    30

  • 8/6/2019 Collectiion of Java and J2EE Questions

    31/35

    V.Parthipan AP/CSE [email protected]

    3) And a Session Bean implementation class.

    8) Explain the role of Home Interface.Home interface contains factory methods for locating, creating and removing instances

    of EJB's.

    9) Explain the role of Remote Interface.Remote interface defines the business methods callable by a client. All methods definedin the remote interface must throw RemoteException.

    10) What is the need for a separate Home interface and Remote Interface. Can'tthey be defined in one interface?EJB doesn't allow the client to directly communicate with an enterprise bean. The clienthas 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 cycleoperations like creating, locating,removing one or more beans. While the remoteinterface is used for remotely accessing the business methods.

    11) What are callback methods?Callback methods are bean's methods, which are called by the container. These arecalled to notify the bean, of it's life cycle events.

    12) How will you make a session bean as stateful or stateless?We have to specify the it in the deployment descriptor(ejb-jar.xml) using tag.

    13) What is meant by Activation?The process of transferring an enterprise bean from secondary storage to memory.

    14) What is meant by Passivation?The process of transferring an enterprise bean from memory to secondary storage.

    15) What is a re-entrant Entity Bean?An re-entrant Entity Bean is one that can handle multiple simultaneous, interleaved, ornested invocations which will not interfere with each other.

    16) Why are ejbActivate() and ejbPassivate() included for stateless session beaneven 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 toimplement for Stateful Session Bean and Stateless Session Bean. Both Stateless andStateful Session Bean implement javax.ejb.SessionBean and this would not be possibleif stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

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

    18) Explain the role of EJB Container?EJB Container implements the EJB component contract of the J2EE architecture. It

    31

  • 8/6/2019 Collectiion of Java and J2EE Questions

    32/35

    V.Parthipan AP/CSE [email protected]

    provides a runtime environment for enterprise beans that includes security, concurrency,life cycle management, transactions, deployment, naming, and other services. An EJBContainer is provided by an EJB Server.

    19) What are Entity Bean's?Entity Bean is an enterprise bean that represents persistent data maintained in adatabase. An entity bean can manage its own persistence or can delegate this functionto its container. An entity bean is identified by a primary key. If the container in which anentity bean is hosted crashes, the entity bean, its primary key, and any remotereferences survive the crash.

    20) What is a Primary Key?Primary Key is an object that uniquely identifies an entity bean within a home.

    20) Can we specify primitive data type be as a primary key?Primitive data type cannot be directly used as primary key, it should be wrapped using awrapper class.

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

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

    23) What are the difference's between a Local Interface and a Remote Interface?Local Interfaces are new mechanism introduced in EJB 2.0 specification which enablescomponents 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 downsideis a loss of flexibility: because bean and client must run in the same container, thelocation 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 byreference.

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

    32

  • 8/6/2019 Collectiion of Java and J2EE Questions

    33/35

    V.Parthipan AP/CSE [email protected]

    25) What are ejbHome methods or Home Business Methods?EJB 2.0 allows entity beans to declare ejbHome methods in the home interface. Thesemethods perform operations that are not specific to a particular bean instance.

    26) What is a transaction?A transaction is a sequence of operations that must all complete successfully, or leavesystem in the state it had been before the transaction started.

    27) What do mean by ACID properties of a transaction?ACID is the acronym for the four properties guaranteed by transactions: atomicity,consistency, isolation, and durability.

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

    29) What are container managed transactions?In an enterprise bean with container-managed transactions, the EJB container sets theboundaries of the transactions. You can use container-managed transactions with anytype of enterprise bean: session, entity, or message-driven. Container-managedtransactions simplify development because the enterprise bean code does not explicitlymark the transaction's boundaries. The code does not include statements that begin andend the transaction.

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

    31) What are bean managed transactions?For bean-managed transactions, the bean specifies transaction demarcations usingmethods in the javax.transaction.UserTransaction interface. Bean-managed transactionsinclude 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 notmatch. If they do not match, EJB container maintains associations between the beanand the nonterminated transaction.

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

    32) What is the difference between container managed and bean managed

    33

  • 8/6/2019 Collectiion of Java and J2EE Questions

    34/35

    V.Parthipan AP/CSE [email protected]

    transaction?In container-managed transaction, the transaction boundaries are defined by thecontainer while in bean managed transaction, the transaction boundaries are defined bythe bean. Entity Beans transactions are always container managed.

    32) Why entity bean's transaction can't be managed by the bean?Entity bean's represent the data and responsible for the integrity of the data. Entitybean's doesn't represent business operations to manage transactions. So there is norequirement for an entity bean managing it's transaction.

    33) How many types of transaction attributes are available in EJB and what arethey?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 issuspended during the time of the method execution.2. Required : If the method is called within a transaction, the method is executed in thescope of this transaction; otherwise, a new transaction is started for the execution of themethod and committed before the method result is sent to the caller.3. RequiresNew : The method will always be executed within the scope of a newtransaction. The new transaction is started for the execution of the method, andcommitted before the method result is sent to the caller. If the method is called within atransaction, this transaction is suspended before the new one is started and resumedwhen 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 callerdoes not have an associated transaction, the method is invoked without a transactionscope.6. Never : The client is required to call the bean without any transaction context; if it isnot the case, a java.rmi.RemoteException is thrown by the container.

    34) How many types of Isolation Level's are available in EJB and what are they?

    35) Are we allowed to change the transaction isolation property in middle of atransaction?No. You cannot change the transaction isolation level in the middle of transaction.

    36) Are enterprise beans allowed to use Thread.sleep()?Enterprise beans are restricted from invoking multithreading thread functionality.

    37) Can a bean be attached to more than one JNDI name?Yes. A same bean can be deployed multiple times in the same server with different JNDInames.

    38) Can a client program directly access an Enterprise bean?No. EJB Clients never access an EJB directly. The container insulates the beans fromdirect access from client applications. Every time a bean is requested, created, ordeleted, the container manages the whole process.

    34

  • 8/6/2019 Collectiion of Java and J2EE Questions

    35/35

    V.Parthipan AP/CSE [email protected]

    39) When is an application said to be distributed?An application is distributed when its components are running in separate runtimeenvironments(JVM's), usually on different platforms connected via a network.

    Distributed applications are usually of 3 types. They are :1. two tier (client and a server)2.three tier (client and a middleware and a server)3. multitier (client and multiple middleware and multiple servers).

    40) What is an EAR file?EAR is Enterprise Archive file. A archive file that contains a J2EE application.

    41) What do mean by business method?A method of an enterprise bean that implements the business logic or rules of anapplication.

    42) What is a finder method?A method defined in the home interface and invoked by a client to locate an entity bean.