300+ [LATEST] Adv Java Interview Questions and Answers

Q1. Can A For Statement Loop Indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;

Q2. What Is A Hibernatetemplate?

HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into DataAccessExceptions which is an unchecked exception. HibernateTemplate is typically used to implement data access or business logic services. The central method is execute(), that supports the Hibernate code that implements HibernateCallback interface.

Q3. Which Characters May Be Used As The Second Character Of An Identifier, But Not As The First Character Of An Identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

Q4. How Do You Communicate In Between Applets And Servlets?

We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and “tunnel” to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn’t know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

Q5. What Is Meant By Method Chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining. 

SessionFactory sessions = new Configuration()
.setProperties( System.getProperties() )

Q6. What Should Sessionfactory Be Placed So That It Can Be Easily Accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate. session_ factory_ name in the hibernate. properties file.

Q7. What Is The Relationship Between Enterprise Javabe And Javabe?

Enterprise JavaBe extends the JavaBe component model to handle the needs of tractional business applications.

JavaBe is a component model for visual construction of reusable components for the Java platform. Enterprise JavaBe extends JavaBe to middle-tier/server side business applications. The extensions that Enterprise JavaBe adds to JavaBe include support for tractions, state management, and deployment time attributes.

Although applications deploying the Enterprise JavaBe architecture are independent from the underlying communication protocol, the Enterprise JavaBe architecture specifies how communication among components maps into the underlying communication protocols, such as CORBA/IIOP.

Q8. What Is The Log That Has To Seen To Check For An Error In Ruby Rails?

Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you’re having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application’s execution.

Q9. What Is The Relationship Between The Canvas Class And The Graphics Class?

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

Q10. What Is Attribute Oriented Programming?

XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

Q11. Can I Use Javascript To Submit A Form?

You can submit a form with a link as below. BTW, the examples below assume you are in an block and ‘myForm’ is picked up from the struts-config.xml name field of the action. 

document.forms[“myForm”].submit();’ />
document.forms[“myForm”].submit();’ />
… the java part …
class MyAction extends ActionForm implements Serializable {

public ActionForward execute (ActionMapping map, ActionForm form,
HttpServletRequest req, HttpServletResponse) {

String myAction = req.getParameter(“myAction”);

if (myAction.equals(“save”) {
// … save action …
} else if (myAction.equals(“delete”) {
// … delete action …

This is just one of many ways to achieve submitting a form and decoding the intended action. Once you get used to the framework you will find other ways that make more sense for your coding style and requirements. Just remember this example is completely non-functional without JavaScript.

Q12. Why Would A Developer Need The Javabe Migration Assistant For Activex?

Many of the capabilities that are so exciting to JavaBe developers are not available on ActiveX, or are incomplete. There is, therefore, a need for a set of conversion conventions and tools designed to convert desktop ActiveX components into JavaBe components. The resulting Be will be usable in both in new network savvy e-business applications as well as traditional desktop applications, includingActiveX containers. Developers and customers benefit from the advantages offered by JavaBe by simply leveraging their current investments in ActiveX.

Q13. Write Code Of Any Action Class?

Here is the code of Action Class that returns the ActionForward object. 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping; 
public class TestAction extends Action
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
return mapping.findForward(“testAction”);

Q14. What Class Is The Top Of The Awt Event Hierarchy?

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

Q15. What Is Bean Persistance Property?

A bean has the property of persistence when its properties, fields, and state information are saved to and retrieved from storage. Component models provide a mechanism for persistence that enables the state of components to be stored in a non-volatile place for later retrieval.

Q16. What Are The High-level Thread States?

The high-level thread states are ready, running, waiting, and dead.

Q17. What Is Local Interface. How Values Will Be Passed?

An EJB can use local client view only if it is really guaranteed that other enterprise be or clients will only address the bean within a single JVM. With local client view, you can do pass-by-reference, which me your bean, as well as the client, will work directly with one copy of the data. Any changes made by the bean will be seen by the client and vice versa. Pass-by-reference eliminates time/system expenses for copying data variables, which provides a performance advantage.

Q18. What’s The Difference Between Hibernate And Ejb 3 ? Don’t You Think Ejb 3 Is Just A Clone Of Hibernate ?

The perception of EJB3 as being a simple clone of Hibernate is primarily based on developer familiarity with Hibernate and a similarity of naming, as well as common purpose, and that Hibernate is morphing itself into an EJB3 implementation based on the work going into the specification, not the other way around.

EJBs are supposed to be components, in the sense that they’re not just one class, but a set of classes, descriptors and usage and management contracts. All of this in order to allow a container (JBoss, Weblogic, etc.) to provide services to those components, and to be able to reuse and distribute this components. This services are, among others, tractions, concurrent access control, security, instance pooling, etcetera.

Hibernat is “just” an ORM (Object/Relational Mapping) tool. Quick and dirty, this me you can store an object tree belonging to an class hierarchy in a relational DB without writing a single SQL query. Quite cool, IMO. But no traction control, no instance pooling, no concurrency control, and certainly no security.

Q19. What Is The Difference Between Jfc & Wfc?

JFC supports robust and portable user interfaces. The Swing classes are robust, compatible with AWT, and provide you with a great deal of control over a user interface. Since source code is available, it is relatively easy to extend the JFC to do exactly what you need it to do. But the number of third-party controls written for Swing is still relatively small.
WFC runs only on the Windows (32-bit) user interface, and uses Microsoft extensions to Java for event handling and ActiveX integration. Because ActiveX components are available to WFC programs, there are theoretically more controls available for WFC than for JFC. In practice, however, most ActiveX vendors do not actively support WFC, so the number of controls available for WFC is probably smaller than for JFC. The WFC programming model is closely aligned with the Windows platform.

Q20. Do I Have To Credit Struts On My Own Website?

You need to credit Struts if you redistribute your own framework based on Struts for other people to use. (See the Apache License for details.) But you do not need to credit Struts just because your web application utilizes the framework. It’s the same situation as using the Apache HTTPD server or Tomcat. Not required if its just running your web site.

Q21. What Is The Difference Between The Session.update() Method And The Session.lock() Method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same traction. Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q22. Is A Class A Subclass Of Itself?

A class is a subclass of itself.

Q23. What’s The Difference Between Struts And Turbine? What’s The Difference Between Struts And Espresso?

If you are starting from scratch, packages like Turbine and Espresso can be very helpful since they try to provide all of the basic services that your team is likely to need. Such services include things like data persistence and logging. 

If you are not starting from scratch, and need to hook up your web application to an existing infrastructure, then “plain vanilla” Struts can be a better choice. The core Struts framework does not presuppose that you are using a given set of data persistence, presentation, or logging tools. Anything goes =:0) 

Compared to other offerings, Struts endeavors to be a minimalist framework. We try leverage existing technologies whenever we can and provide only the missing pieces you need to combine disparate technologies into a coherent application. This is great when you want to select your own tools to use with Struts. But, if you prefer a more integrated infrastructure, then packages like Turbine or Espresso (which uses Struts) are perfectly good ways to go.

See also

* < http://www.mail-archive.com/struts-user@jakarta.apache.org/msg03206.html >
* < http://www.mail-archive.com/general@jakarta.apache.org/msg00495.html >
* < http://jakarta.apache.org/velocity/ymtd/ymtd.html >

Q24. What Are The Different Messaging Paradigms Jms Supports?

Publish and Subscribe i.e. pub/suc and Point to Point i.e. p2p.

Q25. Why Do You Need Orm Tool Like Hibernate?

ORM tools like hibernate provide following benefits:
• Improved performance: Lazy loading, Sophisticated caching, Eager loading.
• Improved productivity: High-level object-oriented API, Less Java code to write, No SQL to write.
• Improved maintainability: A lot less code to write.
• Improved portability: ORM framework generates database-specific SQL for you.

Q26. What Interface Must An Object Implement Before It Can Be Written To A Stream As An Object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

Q27. What Is The Vector Class?

The Vector class provides the capability to implement a growable array of objects.

Q28. Under What Conditions Is An Object’s Finalize() Method Invoked By The Garbage Collector?

The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.

Q29. What Are The Different Approaches To Represent An Inheritance Hierarchy?

i. Table per concrete class.
ii. Table per class hierarchy.
iii. Table per subclass.

Q30. Why A Component Architecture For The Java Platform?

JavaBe brings the extraordinary power of the Java platform to component development, offering the ideal environment for a developer who wants to extend the concept of reusable component development beyond one platform and one architecture to embrace every platform and every architecture in the industry.

Q31. How To Control Serialization In Java Be?

Three ways to control serilization in java be:
1.Automatic serialization, implemented by the Serializable interface. The Java serialization software serializes the entire object, except trient and static fields.
2.Customized serialization. Selectively exclude fields you do not want serialized by marking with the trient (or static) modifier.
3.Customized file format, implemented by the Externalizable interface and its two methods. Be are written in a specific file format.

Q32. The Ejb Container Implements The Ejbhome And Ejbobject Classes. For Every Request From A Unique Client, Does The Container Create A Separate Instance Of The Generated Ejbhome And Ejbobject Classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.

Q33. Can The Primary Key In The Entity Bean Be A Java Primitive Type Such As Int?

The primary key can’t be a primitive type–use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)

Q34. What Are The Problems Faced By Java Programmers Who Don’t Use Layout Managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

Q35. What Is The Difference Between Queue And Topic ?

A topic is typically used for one to many messaging , while queue is used for one-to-one messaging. Topic .e. it supports publish subscribe model of messaging where queue supports Point to Point Messaging.

Q36. When Is The Best Time To Validate Input?

This is an excellent question. Let’s step back a second and think about a typical mid to large size application. If we start from the back end and work toward the view we have:
1) Database: Most modern databases are going to validate for required fields, duplicate records, security constraints, etc. 
2) Business Logic: Here you are going to check for valid data relationships and things that make sense for the particular problem you are triing to solve. 
… This is where struts comes into the picture, by now the system should be pretty well bulletproof. What we are going to do is make validation friendlier and informative. Rember it is OK to have duplicate validations… 
3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where you can do your validation and feed back to the view, information required to correct any errors. validate is run after the form has been reset and after the ActionForm properties have been set from corresponding view based input. Also remember you can turn validation off with validate=”false” in the action mapping in the struts-config.xml. This is done by returning an ActionErrors collection with messages from your ApplicationResources.properties file. 
Here you have access to the request so you can see what kinds of action is being requested to fine tune your validations. The tag allows you to dump all errors on your page or a particular error associated with a particular property. The input attribute of the struts-config.xml action allows you to send validation errors to a particular jsp / html / tile page. 
4) You can have the system perform low level validations and client side feedback using a ValidatorForm or its derivatives. This will generate javascript and give instant feedback to the user for simple data entry errors. You code your validations in the validator-rules.xml file. A working knowledge of regular expressions is necessary to use this feature effectively.

Q37. What Is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q38. How Would You Create A Button With Rounded Edges?

There’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.

Q39. What Are Three Ways In Which A Thread Can Enter The Waiting State?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q40. Give The Details Of Xml Files Used In Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. How you will display validation fail errors on jsp page? – The following tag displays all the errors: < html:errors/ >

Q41. What Is The Advantage Of Using Entity Bean For Database Operations, Over Directly Using Jdbc Api To Do Database Operations? When Would I Use One Over The Other?

Entity Be actually represents the data in a database. It is not that Entity Be replaces JDBC API. There are two types of Entity Be Container Managed and Bean Mananged. In Container Managed Entity Bean – Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor).

In the Bean Managed Entity Bean – The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity be you dont need to worry about database traction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features. what suresh told is exactly perfect. ofcourse, this comes under the database trations, but i want to add this. the great thing about the entity be of container managed, whenever the connection is failed during the traction processing, the database consistancy is mantained automatically. the container writes the data stored at persistant storage of the entity be to the database again to provide the database consistancy. where as in jdbc api, we, developers has to do manually.

Q42. How Can I Arrange For Different Applets On A Web Page To Communicate With Each Other?

Name your applets inside the Applet tag and invoke AppletContexts getApplet() method in your applet code to obtain references to the other applets on the page.

Q43. What Are The Applet’s Life Cycle Methods? Explain Them.

Following are the methods in the life cycle of an Applet:
(a) init() method—called, when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually initializes the variables to be used in the applet.
(b) start() method—called each time an applet is started.
(c) paint() method—called when the applet is minimized or refreshed. This method is used for drawing different strings, figures and images on the applet window.
(d) stop() method—called when the browser moves off the applet’s page.
(e) destroy() method—called when the browser is finished with the applet.

Q44. What Do You Understand By The Term Client-server Application?

Networks make many new types of applications possible because a single machine no longer has to do everything. Within a network, some computers, called servers, perform specialized tasks on behalf of other programs. A program that uses a server is a client.
A server is simply a computer that runs a specific program continuously whose role purpose is to provide a service to other programs. A client, on the other hand, is a program that receives service from the server. For example, a print server is a software program that waits until other programs (the clients) send their files to print. The server then prints the files on behalf of the client. There are many types of servers across the Internet with which you may be familiar, such as mail servers, file servers and of course, World Wide (or HTTP) servers.

Q45. Declarative Exception Handling

If you have developed web applications long enough, you will realize a recurring pattern emerges: when the backend (e.g. the EJB tier) throws you an exception, you nearly always need to display an error page corresponding to the type of that exception. Sooner or later, you will come up with a mechanism to use a lookup table (e.g. an HashMap) to lookup an error page from the exception class. 

Struts 1.1 now provides a similar but more powerful mechanism to declare exception handling. In Struts 1.1, you can declare in the struts-config.xml the associations between an exception class and an exception handler. Using the default exception handler included in Struts, you can also specify the path of the error pages. With this information, Struts will automatically forward to the specified pages when an uncaught exception is thrown from an Action. 

Like other facilities in Struts, the exception handlers are pluggable. You can write and define your own handler classes if needed. 

Q46. Difference B/w Paint() And Paintcomponent()?

The Key point is that the paint() method invokes three methods in the following order :
> PaintComponent()
> paintBorder()
> paintChildren()
As a general rule, in Swing, we should be overriding the paintComponent method unless we know what we are doing paintComponent() paints only component (panel) but paint() paints component and all its children.

Q47. What Are The Core Classes Of Struts?

Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

Q48. What Happens When You Invoke A Thread’s Interrupt Method While It Is Sleeping Or Waiting?

When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

Q49. How Are The Elements Of A Cardlayout Organized?

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

Q50. What Happens When You Invoke A Thread’s Interrupt Method While It Is Sleeping Or Waiting?

When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.