Java-J2EE Interview Questions

Posted by Duty Until Death | 9:22 PM | 0 comments »

Q.1 What is the purpose of action servlet and action in struts?

Ans.
Action Servlet is backbone of struts framework. It is the main controller component. Action class contains userlogic. It returns the next view to the FrameWork.

Q.2 What is the difference between struts 1.0 and 1.1 OR what is the difference between perform() and execute() method in struts.

Ans. The struts base Action class has been modified with a new method called execute(). This method should be called instead of the perform() method. The main difference between the two is that the execute() method declares that it throws java.lang.Exception. Where as the earlier perform() method declared that it could throw IOException and ServletException. This change was necessary to facilitate the new declarative exception-handling feature that was added to struts 1.1.As a result the perform() method has been replaced by execute().Below are other differences between 1.0 and 1.1



  • Request processor class added in 1.1
  • Make some changes in web.xml and struts-config.xml files
  • Added declarative exceptionhandling feature
  • DynamicAction Forms
  • Multiple Application Modules.
  • Struts validator framework
  • Change to the ORO package
  • Change to Commons logging

Q.3 How we can manage exception-handling in struts?

Ans. There are basically two type of approaches for exception-handling.

Declarative :: In this approach exception are defined in the struts-config.xml and if the exception occurs the control is automatically passed to the appropriate error page. The tag is basically used to define the exception in the struts-config.xml file.

E.g. <action path="/logon"
type="com.candidsoftwares.LogOnAction" input="/UserDetail.jsp" >

< exception key="errormessage.logon" type="java.lang.RuntimeException" path="error.jsp" >;

</action >

In tag key="the key defines the key present in MessageResource.properties file; type=the class of the exception occured;path=the page where the control is to be followed in case exception occured;Handler=the exception handler which will be called before passing the control to the file specified in path attribute.

Another way is to define the exceptions globally by using the key.

<global-exceptions>
<exception key=”error.logon” type=”java.lang.RuntimeException” path=”/error.jsp”/>
</global-exceptions>

Programmetically --In this approach the exceptions are caught using normal java language try/catch block and instead of showing the exception some meaningful messages are displayed. In this approach the flow of control is also maintained by the programs.

Q.4 How to convert java object into byte array?

Ans. below metion code to conver java object into byte array.

public static byte[] ObjectToByte(Object obj) throws java.io.IOException {

ByteArrayOutputStream bos= new ByteArrayOutputStream();

ObjectOutputStream oos= new ObjectOutputStream();

oos.writeobject(obj);

oos.close();

bos.close();

byte[] data = bos.toByteArray();

return data;

}

Q.5 What are the benefits of ORM and hibernate?

Ans. There are many benefits from these. Out of the following are the most important one.
Productivity :: Hibernate reduces the burden of developer by providing much of funtionality and let the developer to concentrate on business logic.

Maintainability ::As hibernate provides most of the functionality, let the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.

Performance::Hand-coded persistence greater than automated one.But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. It it is automated persistence then it still increases the performance.

Vendor independence::Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

Q.6 what are core interfaces are of hibernate framework?

Ans. Below are the main interfaces used in hibernate.

Session Interface:: This is the primary interfaces used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.

SessionFactory Interface::This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application thereads.

Configuration Interface::This interface is used to configure and bootstrap hibernate.The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.

Transaction Interface::This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstrats the code from any kind of transaction implementation such as JDBC transaction, JTA transaction.

Query and criteria Interface::This interface allows the user to perform queries and also control the flow of the query execution.

Q.7 What are the three statements in JDBC & differences between them.

Ans. There are basically three types of statements in JDBC.

1) Statement :: Basically used to execute single SQL statement. We used createStatement() method for that.

2) Prepared Statement::Used to execute SQL statements over and over.Prepared statement is compiled only once even though it is used n number of times.We used preparedStatement()

3) Callable Statement::Used to execute multiple sql statements over and over,used to call stored procedure.We used call() method.

Q.8 What is the difference between store procedure and function.

Ans. Proceduare are parsed and compiled, they are stored in compiled format in the database where as Function are compiled and executed at runtime.

  1. Function must return a value, procedures don't need to.
  2. You can have DML statements in function,but you can not call such a functgion in SQL query.If you have a function that is updating a table, you cannot call that function from a SQL query. -- select test(field name) from XYZtablename;will throw error.

Q.9 What is serialization?

Ans. Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.whenever an object is sent over the network,objects need to be serialized.Moreover if the state of an object is to be saved, objects need to be serialized.

Q.10 What is externalizable interface?

Ans. Externalizable is an interface which contains two methods readExternal and writeExternal.These methods give you a control over the serialization mechanism.Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

Q.11 What is synchronization and why is it important?

Ans. With respect to multithreading synchornization is the capatcity to control the access of multiple threads to shared resources,. Without synchornization,it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value.

Q.12 what one should take care of while serializing the object?

Ans. One should make sure that all the included objects are serializable.If any of the objects is not serializable then it throws a NotSerializableException.

Q.13 What happens to the static field of a class during serialization?

Ans. There are three exceptions in which serialization doesn't read and write to the stream.

  1. serialization ignores static fields, because they are not part of any particular state.
  2. base class fields are only handled if the base class itself is serializable.
  3. transient fields.

Q.14 What are checked exceptions and unchecked exceptions in java?

Ans. A checked exception is some subclass of Exception(or Exception itself),excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown.

While unchecked exception are RuntimeException and any of its subclasses.Class Error and its subclasses also are unchecked.With an unchecked exception,however, the compiler doesn't force client either to catch the exception or declare it in a throws clause.In fact, client programmers may not know that the exception could be thrown.

Checked exceptions must be caught at compile time.Runtime exceptions do not need to be.

Q.15 whats the difference between notify() and notifyAll()?

Ans. notify() is used to unblock one waiting thread;notifyAll() is used to unblock all of them; Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change(for example, when freeing a buffer back into a pool).notifyAll() if multiple threads should resume(for example, when releasing a "writer" lock on a file might permit all "readers" to resume.)

Q.16 what are synchronized methods and synchornized statements?

Ans. Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class.Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Q.17 what is the purpose of the wait(),notify() and notifyall() methods?

Ans. The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate with each other.

Q.18 What are the high-level thread states?

Ans. Below are high-level thread states.

  1. ready
  2. running
  3. waiting
  4. dead

Q.19 What is the difference between yielding and sleeping?

Ans. When a task invokes its yield() method,it returns to the ready state.When a task invokes its sleep() method, it returns to the waiting state.

Q.20 What happens when a thread cannot acquire a lock on object?

Ans. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Q.21 How many methods in Object class?

Ans. Below are available methods in Object class.

  1. clone()
  2. equals() and hashcode()
  3. getClass()
  4. finalize()
  5. wait() & notify()
  6. toString()

Q.22 What is the relationship between synchronized and volatile keyword?

Ans. The JVM is guaranteed to treat and writes of data of 32 bits or less as atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in future). For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or blcok, or declare them volatile.

Q.23 How do you create a read-only collections?

Ans. The Collections class has six methods to help out here.

  1. unmodifiableCollection(Collection collection)
  2. unmodifiableList(List list)
  3. unmodifiableMap(Map map)
  4. unmodifiableSet(Set set)
  5. unmodifiableSortedMap(SortedMap sortedmap)
  6. unmodifiableSortedSet(SortedSet sortedset)

If you get an Iterator from one of these unmodifiable collections,when you call remove(), it will throw an UnsupportedOperationException.

Q.24 How we can implement a thread-safe JSP page?

Ans. We can make jsp thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@page isThreadSafe="false" %> within your JSP Page.

Q.25 What are the lifecycle phase of a JSP?

Ans. JSP Pages looks like HTML page but is a servlet.

  1. Page transalation :: page is parsed, and a java file which is a servlet is created.
  2. Page compilation :: page is compiled into a class file.
  3. Page loading :: This class file is loaded.
  4. Create an instance :: Instance of servlet is created.
  5. jspInit() method is called.
  6. jspService() is called to handle service calls
  7. jspDestroy() is called to destroy it when the servlet is not required.

Q.26 What are the implicit objects? List them.

Ans. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:

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

Q.27 What are different scope values for the <jsp:usebean>

Ans. The different scope values for are:

  • Page
  • Session
  • request
  • application

Q.28 What is the difference between WebServer and ApplicationServer?

Ans.
Webserver contains servlet engine and jsp engine. It does not provide system-level services like security management, transaction management,resource pooling etc...application server contains servlet container,jsp container and EJB contrainer. And it provides system-level services implicitly. WebServer is protocol dependent while application server is protocol independent.

Q.29 Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap mainted by the JVM?

Ans. Yes, the JVM maintain a cache by itself. No it allocates the objects in stack, in heap on references. Heap maintained by the JVM because, every time the JVM should not use objects directly it uses only references that's why the heap maintained by the JVM.

Q.30 what is the main difference between jdk1.4 and jdk1.5?

Ans
. jdk 1.5 has various features which was not in jdk1.4 , These few features are below.



  1. Annotation
  2. Autoboxing
  3. Enum Support
  4. ForEach
  5. Generic implementatijon of class method wildcards bounded type.
  6. variable argument support.

Q.31 Benefits of Spring MVC over Struts?

Ans. Spring provides a very clean division between controllers,JavaBean models, and views.

  • Spring's MVC is very flexible. Unlike struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java),Spring MVC is entirely based on interfaces.Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interfaces.Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
  • Spring, like webwork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
  • Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to;You can use Velociy,XSLT or other view technologies. If you want to use a custom view mechanism - for example, your own templating language- you can easily implement the spring interface to integrate it.
  • Spring controller are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
  • Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
  • The web tier becomes a thin layer on top of business object layer. This encourage good practice.Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.
  • No ActionForms.Bind directly to domain objects.
  • More testable code(validation has no dependency on servlet API)
  • Struts imposes dependencies on your Controller (they must extend a Struts class), Spring doesn't force you to do this although there are convenience Controller implementation tha tyou can choose to extend.
  • Struts has a well-defined interface to business layer.
  • Spring offers better intergration with view technologies other than JSP(Velociy/XSLT/FreeMaker/XL etc.)

Q.32 Why are wait(),notify() and notifyall() methods defined in the Object class?

Ans. These methods are detailed on Java Software Developement Kit JavaDoc page for the Object class, they are to implement threaded programming for all subclasses of object.

Q.33 Why are there seperate wait and sleep methods?

Ans. The static Thread. sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run.

Q.34 Can i implement my own start() method?

Ans. The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

Q.35 How do I serialize an object to a file?

Ans. To serialize an object into a stream perform the following actions.

  • open one of the output streams.
  • chain it with the ObjectOutputStream
  • call the method writeObject() providing the instance of a Serializable object as an argument.
  • close the streams.

try {

fout = new FileOutputStream("tests.dat");

out = new ObjectOutputStream(fout);

out.writeObject(theQueue);

}catch(IOException exp){

e.printStackTrace();

}

Q.36 How do I deserialize an object?

Ans. To deserialize an object, perform the following steps:

- Open an input stream.

- Chain it with the ObjectOutputStream - Call the method readObject() and cast the returned object to the class that is being deserialized.

- Close the stream.

try {

fin = new FileInputStream("testst.dat");

in = new ObjectOutputStream(fin);

// de-serializing theQueue.

theQueue = (Queue) in.readObject();

in.close();

} catch (Exception exp) {

exp.printStackTrace();

}

Q.37 What is the difference between an interface and an Abstract class?

Ans. An abstract class can have instance methods that implement a default behaviour. An interface can only declare contants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.

  1. Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  2. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods etc..
  3. A class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  4. Interface are slow as it requires extra indirection to find corresponding method in the actual class. Abstract class are fast.

Q.38 What is the difference between "==" and "equals()" method?

Ans. "==" does shallow comparison, It returns true if two object points to the same address in the memory.While, "equals() " does deep comparison, it checks if the values of the data in the object are same.

Q.39 What is the difference between String and StringBuffer.

Ans. String is an immutable class, immutable means we can't change the value.

E.g String str = "test" // suppose memory address is 54321.

Now, we are trying to assign a new value to the variable str then

str = "test java" ; then the value of the variable at address 54321 will not change but a new momory is allocated for this variable say 12345. So, in the memory address 54321 hava "test" and the memory address 12345 will have value "test java" and the variable str will now be pointing to address 12345 in memory.

StringBuffer can be modified dynamically.

E.g. StringBuffer strt = "java" // address in memory is say 12345 and now if you assign a new value to the variable str then str = "core java" ; then value in the address of memory will get replaced, a new memory address is not allocated in this case.

_________________________________________________________________

Q.40 What are different types of inner classes?

Ans. Inner classes nest within another classes. A normal class is a direct member of a package. Basically four type of inner classes are available.

  1. Static member classes.
  2. Member classes.
  3. Local classes.
  4. Anonymous classes.

Static member classes :: a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level class.

Member classs ::a member class is also defined as a member of a class. Unlike the static variety,

_________________________________________________________________

Q.41 Explain OOPS principles?

Ans. 1) Abstraction :: It means hiding the details and only exposing the essential parts.

2)Polymorphism :: Polymorphism means having many forms. In java you can see polymorphism when you have multiple methods with the same name.

3)Inheritance ::Inheritance means the child class inherits the non private properties of the parent class.

4) Encapsulation::It means data hiding. In java with encapsulation the data by making it private and even we want some other class to work on that data then the setter and getter methods are provided.

Q.42 What is the difference between queue and stack?

Ans. Stack work on Last-in-first-out while queue work on First-in-first-out rule.

Q.43 Difference between SAX and DOM parser.

Ans. DOM parser are Object based while SAX parsers are event based.DOM parsers creates Tree in the memory whereas SAX parser does not and hence it is faster than DOM.DOM parser are useful when we have to modify the XML,with SAX parser we can't modify the XML, it is read only.

Q.44 why do we need public static void main(String args[])

Ans. public : The method can be accessed outside the class/package.

static : You need not have an instance of the class to access the method.

void : Your application need not return a value, as the JVM launcher would return the value when it exits.

main() : This is the entry point for the application.

Q.45 what is the difference between DROP,DELETE and TRUNCATE in Oralce?

Ans. DROP and TRUNCATE are DDL commands while DELETE is a DML command.

  • DROP and TRUNCATE are autocommited, while DELETE is not autocommited.
  • DELETE command removes all the rows from the table and the deleted records get logged into transaction log which slow down the performance.While truncate table also deletes the records from the table but does not log the deleted record.
  • By using TRUNCATE and DELETE we can delete the records from the database.Difference is by using DELETE we can retrieve datas using ROLLBACK but this can't be done in the case of TRUNCATE.

Q.46 What is the difference between StringBuffer and StringBuilder?

Ans. The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized while StringBuffer is synchronized.So when the application run in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

0 comments