Java FAQs

                                                                                                                                                                
Why threads block or enter to waiting state on I/O?
Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.

What are transient variables in java?
Transient variables are variable that cannot be serialized.

How Observer and Observable are used?
Subclass of Observable class maintains a list of observers. Whenever an Observable object is updated, it invokes the update () method of each of its observers to notify the observers that it has a changed state. An observer is any object that implements the interface Observer. 

What is synchronization
Synchronization is the ability to control the access of multiple threads to shared resources. Synchronization stops multithreading. With synchronization, at  a time only one thread will be able to access a shared resource.

What is List interface?
List is an ordered collection of objects.

What is a Vector
Vector is a growable array of objects.

What is the difference between yield () and sleep ()?
When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.

What are Wrapper Classes?
They are wrappers to primitive data types. They allow us to access primitives as objects.

Can we call finalize () method?
Yes.  Nobody will stop us to call any method, if it is accessible in our class. But a garbage collector cannot call an object's finalize method if that object is reachable.

What is the difference between time slicing and preemptivescheduling?
In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks. 

What is the initial state of a thread when it is created and started?
The thread is in ready state.

Can we declare an anonymous class as both extending a class and implementing an interface?
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both

What are the differences between Boolean& operator and  & operator
When an expression containing the & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed.  && is also called short cut and.

What is the use of the finally block?
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally will not execute when the user calls System.exit ().

What is an abstract method?
An abstract method is methods that don’t have a body. It is declared with modifier abstract.

How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);

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.

Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.

Question: How you can force the garbage collection?
Garbage collection automatic process and can’t be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can’t directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

What’s the difference between constructors and normal methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.

Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets: 
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network   Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

What’s the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.

13.Can an inner class declared inside of a method access local variables of this method?It’s possible if these variables are final.

Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}

Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a  wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean  – java.lang.Boolean
byte – java.lang.Byte
char – java.lang.Character
double – java.lang.Double
float – java.lang.Float
int – java.lang.Integer
long – java.lang.Long
short – java.lang.Short
void – java.lang.Void
                                                                                                                                                                          back

                                                                                                                                                           
What is JFC 
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.

 What is AWT?
AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons. The Java Virtual Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating system. 

 What are the differences between Swing and AWT?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.

 What are heavyweight components?
 A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).

 What is lightweight component?
A lightweight component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter").

What is double buffering?
Double buffering is the process of use of two buffers rather than one to temporarily hold data being moved to and from an I/O device. Double buffering increases data transfer speed because one buffer can be filled while the other is being emptied. 

What is an event?
Changing the state of an object is called an event.

 What is an event handler?
An event handler is a part of a computer program created to tell the program how to act in response to a specific event.

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

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

Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.

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

What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.

Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.

Which method of the Component class is used to set the position and size of a component?
setBounds.

                                                                                                                                               back

                                                                                                                                                                
What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment

What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has its own stored procedure language,

What is JDBC Driver?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.

What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.

What is DriverManager?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.

What is a ResultSet?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database. 
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

What is Connection?
Connection class represents  a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. 
A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the get Metadata method.

What does Class.forName return?
A class as loaded by the classloader.

What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

What are the different JDB drivers available?
There are mainly four types of JDBC drivers available. They are:
Type 1: JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. 
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. 
Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver.  Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi-threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading.

 What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace while the database is running and is being accessed by the users

What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.

How do you handle your own transaction?
Connection Object has a method called setAutocommit (boolean flag). For handling our own transaction we can set the parameter to false and begin your transaction. Finally commit the transaction by calling the commit method



                                                                                                                                      back

                                                                                                                                                           
What is a Servlet?
A servlet is a Java program which requires a Web or application server to run. It forms a middle layer between requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Servlet offer an efficient platform-independent replacement for CGI scripts. Servers that can host servlets are Java-enabled servers that respond to client requests.

What is the difference between GenericServlet and HttpServlet?
Generic servlet as the name suggests aims to provide the middle tier solution for non-Http based application like FTP, which means these are protocol independent and can handle multiple types of protocols. While HttpServlet are used for Http based application and can only be implemented for Hyper Text Transfer Protocols.

State few brief points on how Servlet technology excels over CGI scripts?
The following points show how servlet technology excels over the traditional CGI scripts: -
CGI      
Servlet

1. Written in C,C++, VB and Perl which are all platform dependant.         
1. Written in platform independent Java language.
2. For each request heavy weight process is created.     
2. Each request is handled by light weight thread.
3. Difficult to maintain, non-scalable and non-manageable          
3. Increased scalability, reusability (component based model).
4. Prone to security problems of programming language
4. Leverages built in security of Java language.

 Discuss the basic structure of a Servlet.
The basic structure of a servlet is summarized as: -
It uses simple Java codes within it.
The javax.servlet and the javax.servlet.http packages provides the classes and interfaces for writing servlets.
It is a sub class of HttpServlet class.
It generally throws ServletException and IO Exceptions.
It overrides the doGet and doPost methods
There are two arguments of doGet or doPost method

a.HttpServletRequest b.HttpServletResponse

Discuss briefly about the methods called in a life cycle of a servlet
The init method - The init method is invoked when the servlet is first created and initializes the global variables and loads the classes into memory. This method is not called again.

The service Method: After creating a servlet each time the server receives a request the server creates a new thread and calls service.

The destroy Method: If the server decides to unload a servlet instance, it first call the destroy method. This method gives a chance to close database connection and other cleanup activities.


What is session tracking? State its uses.
HTTP is a state less protocol and requires some technique by which user data can be maintained persistently between pages. Session tracking helps in solving this. Session tracking can be done in following ways:-

1. Cookies – Storing a small client side data, which is used to hold that particular user specific data only.

2. Hidden data fields – Hidden fields of a page is used to store serializable objects.

3. Session state variables – Memory portion of the web server is assigned to hold data.

4. URL rewriting – URL itself can contain data like in a query string where a page’s data is attached with the URL to pass client’s specific data.



What is ServletContext used for?
ServletContext is used by servlets to implement the following points :-


1. Set and get context-wide (application-wide) objectvalued attributes
2. Get request dispatcher to forward to or include web component
3. Access Web context-wide initialization parameters set in the web.xml file
4. Access Web resources associated with the Web context log.
5. Access other misc. information.

 Discuss the scope of ServletContext.
It is shared by all servlets and JSP pages within a "web application"
A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace and possibly installed via a *.war file
There is one ServletContext object per "web application" per Java Virtual Machine

How to gain access to a getRequestDispatcher?
The getRequestDispatcher() method takes the requested resource's URL as an argument. The format of this argument is a slash ("/") followed by one or more slash-separated directory names, and ending with the name of the resource. The following are examples of valid URLs:

· /ardent/myservlet
· /ardent/tests/MyServlet.class
· /myinfo.html

What is a cookie?
It is a small amount of data sent by a servlet to the web browser.A cookie saves precious server memory and can maintain state through its unique client identification property. The browser knows where and how to save this data and later send back the same to the server on request. A cookie has a name, a single value and optional attributes and it can uniquely identify a client. The server uses cookie to extract the information about the sessions.


Discuss few disadvantages of cookies.
Since a cookie may contain user information like userid, passwords, there remains a chance of cookie hijacking where a client’s cookie is used by another to gain access to other’s account. Again privacy problem occurs when sites rely on cookies for overly sensitive data. The coders have to keep extra checking since a client may disable cookie by default and also have to think some other possible way out for which he needed that cookie.

What is the difference between ServletContext and ServletConfig?
These both are interfaces. ServletConfig interface is implemented to route configuration information to a servlet. The server sends an object which in turn implements the ServletConfig interface to the servlet's init() method. The ServletContext interface informs about the running environment to the servlets. In order to write events to a log file a standard way is also provided.

 What is ActionMapping ?
Action mapping is a technique of forwarding request/response by specifying an action class for URL and different target view. Also the page to which the control shall be passed when a validation error will be raised can be specified too. It is also specified which form bean will correspond to action

<action-mappings>

<action path="/a" type=myclasse.A name="myForm">

<forward name="succes" path="/success.jsp"/>

<forward name="failure" path="/failure.jsp"/>

<action/>

</action-mappings>


What is the difference between JSP and Servlets?
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc. 

What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library 
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags 
Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

What are the different ways for session tracking?
Cookies, URL rewriting, HttpSession, Hidden form fields 

What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

Difference between GET and POST?
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. Query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.
In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

What is session?
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.

What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

What is servlet context?
The servlet context is an object that contains information about the Web application and container.  Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

What is a servlet?
Servlet is a java program that runs inside a web container.

Can we use the constructor, instead of init(), to initialize servlet?
Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, and expressions.

How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. 

How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
In request.getRequestDispatcher (path) in order to create it we need to give the relative path of the resource. But in   resourcecontext.getRequestDispatcher (path) in order to create it we need to give the absolute path of the resource. 

What are the lifecycle of JSP?
When presented with JSP page the JSP engine does the following 7 phases.
Page translation: -page is parsed, and a java file which is a servlet is created.
Page compilation: page is compiled into a class file
Page loading: This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.

What are context initialization parameters?
Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.

What is an Expression?
Expressions are act as place holders for language expression; expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

What is a Declaration?
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .  Generally a scriptlet can contain any java code that is valid inside a normal java method. This will become the part of generated servlet's service method.

    back


                                                                                                                                                      
What is EJB?
Enterprise JavaBeans (EJB) technology is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.

What are the different type of Enterprise JavaBeans ?
There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans.

What is Session Bean?
Session bean represents a single client inside the J2EE server. To access the application deployed in the server the client invokes methods on the session bean. The session bean performs the task shielding the client from the complexity of the business logic.  
Session bean components implement the javax.ejb.SessionBean interface. Session beans can act as agents modeling workflow or provide access to special transient business services. Session beans do not normally represent persistent business concepts. A session bean corresponds to a client server session. The session bean is created when a client requests some query on the database and exists as long as the client server session exists.

What are different types of session bean?
There are two types of session beans, namely: Stateful and Stateless.

What is a Stateful Session bean?
Stateful session bean maintain the state of the conversation between the client and itself. When the client invokes a method on the bean the instance variables of the bean may contain a state but only for the duration of the invocation. 
A Stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.

What is stateless session bean?
Stateless session beans are of equal value for all instances of the bean. This means the container can assign any bean to any client, making it very scalable. 
A stateless session bean is an enterprise bean that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless". Stateless session beans are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior. Typically an application requires less number of stateless beans compared to stateful beans.

What is an Entity Bean?
An entity bean represents a business object in a persistent storage mechanism. An entity bean typically represents a table in a relational database and each instance represents a row in the table. Entity bean differs from session bean by: persistence, shared access, relationship and primary key. T

What are different types of entity beans?
There are two types of entity beans available. Container Managed Persistence (CMP), Bean managed persistence (BMP).

What is CMP (Container Managed Persistence)?
The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. So, your entity beans are more portable.

What is BMP (Bean managed persistence)?
Bean managed persistence (BMP) occurs when the bean manages its persistence. Here the bean will handle all the database access. So the bean's code contains the necessary SQLs calls. So it is not much portable compared to CMP. Because when we are changing the database we need to rewrite the SQL for supporting the new database.

What is abstract schema?
In order to generate the data access calls, the container needs information that you provide in the entity bean's abstract schema. It is a part of Deployment Descriptor. It is used to define the bean's persistent fields and relationships.  

When we should use Entity Bean?
When the bean represents a business entity, not a procedure. We should use an entity bean. Also when the bean's state must be persistent we should use an entity bean. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).

When to Use Session Beans?
At any given time, only one client has access to the bean instance. The state of the bean is not persistent, existing only for a short period (perhaps a few hours). The bean implements a web service. Under all the above circumstances we can use session beans.

When to use Stateful session bean?
The bean's state represents the interaction between the bean and a specific client. The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Under all the above circumstances we can use a Stateful session bean.

When to use a stateless session bean?
The bean's state has no data for a specific client. In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order. The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month. Under all the above circumstance we can use a stateless session bean.

    back
                                                                                                                                                                
What is JMS
The Java Message Service (JMS) API is a messaging standard that allows application components based on the Java 2 Platform, Enterprise Edition (J2EE) to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous

What type messaging is provided by JMS?
Both synchronous and asynchronous are provided by JMS.

What is messaging?
Messaging is a mechanism by which data can be passed from one application to another application.

What are the advantages of JMS?
One of the principal advantages of JMS messaging is that it's asynchronous. Thus not all the pieces need to be up all the time for the application to function as a whole.

What is synchronous messaging?
Synchronous messaging involves a client that waits for the server to respond to a message. So if one end is down the entire communication will fail.

What is asynchronous messaging?
Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. So even if the client is down , the messaging will complete successfully.

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.

What is Stream Message?
Stream messages are a group of java primitives. It contains some convenient methods for reading the data.  However Stream Message prevents reading a long value as short. This is so because the Stream Message also writes the type information along with the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.

What is Map message?
map message contains name value Pairs.  The values can be of type primitives and its wrappers. The name is a string.

What is text message?
Text messages contains String messages (since being widely used, a separate messaging Type has been supported). It is useful for exchanging textual data and complex character data like XML.

What is object message?
Object message contains a group of serializeable java object. So it allows exchange of Java objects between applications. So both the applications must be Java applications.

What is Byte Message?
Byte Messages contains a Stream of uninterrupted bytes.  Byte Message contains an array of primitive bytes in its payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client.

What is the difference between Byte Message and Stream Message?
Bytes Message stores data in bytes.  Thus the message is one contiguous stream of bytes. While the Stream Message maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. Bytes Message allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the Stream Message. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

What is the Role of the JMS Provider?
The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.

What are the different parts of a JMS message?
A JMS message contains three parts. a header, an optional properties and an optional body.

                                                                                                                                                         How do you invoke an applet that is packaged as a JAR file?
 To invoke an applet packaged as a JAR file, open a page containing the applet:
<applet code=AppletClassName.class
        archive="JarFileName.jar"
        width=320 height=240>
</applet>
What is the purpose of the -e option in a jar command?
This option is available since Java SE 6. It sets the entrypoint as the application entry point for stand-alone applications bundled into executable jar file. The use of this option creates or overrides the Main-Class attribute value in the manifest file. This option can be used during creation of jar file or while updating the jar file. This option specifies the application entry point without editing or creating the manifest file. For example, this command creates Main.jar where the Main-Class attribute value in the manifest is set to Main:
jar cfe Main.jar Main Main.class
What is the significance of the manifest in a JAR file?
A JAR file's manifest provides meta-information about the other contents of the JAR file. The manifest itself resides in META-INF/MANIFEST.mf. The meta-information can include
o   Dependencies on other jar files
o   The name of a class to run when "java -jar file.jar" is invoked
o   Versioning information
o   Security information
How do you modify a JAR's manifest file?
Typically, modifying the default manifest involves adding special-purpose headers to the manifest that allow the JAR file to perform a particular desired function.
To modify the manifest, you must first prepare a text file with a complete and valid manifest file. You then use the JAR tool's m option to add the information in your file to the manifest.
The manifest file your prepare must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
   GotoTop