Thursday, January 31, 2013

Memory Leaks

In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code.

A memory leak,occurs when a computer program consumes memory but is unable to release it back to the operating system.The JVM reserves the heap as virtual memory on startup and doesn't gives that memory back until it exits. This virtual memory turns into main memory as it is used. This is why the virtual size and the resident size for a JVM can be very different and the resident memory can grow without the virtual memory changing.

The GC can always find every object on the heap, even those which are not reachable to the application. As such there is no object which is not reachable to running code.however, many people refer to any unwanted increase in memory usage as a memory leak,though this is not strictly accurate from a technical perspective.

In Java, the amount of memory required cannot be determined without a full GC. It is normal to see the "used" memory of a Java application sawtooth. Returning to the same amount of memory used after each GC indicates the memory required has not increased.

A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down unacceptably due to thrashing.

Tuesday, January 22, 2013

Reads and Write binary data

This example reads and write binary data, moving it from disk to memory, and then back again.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**  
 Converting binary data into different forms. 
 Reads binary data into memory, and writes it back out.
 Buffering is used when reading and writing files, to minimize the number 
 of interactions with the disk.
*/
public final class BytesStreamsAndFiles {

  /** Change these settings before running this class. */
  private static final String INPUT_FILE_NAME = "home\s\Download\green_house.jpg";
  private static final String OUTPUT_FILE_NAME = "home\s\Download\green_house_n.jpg";

  /** Run the example. */
  public static void main(String... aArgs) {
    BytesStreamsAndFiles test = new BytesStreamsAndFiles();
    //read in the bytes
    byte[] fileContents = test.read(INPUT_FILE_NAME);
    //test.readAlternateImpl(INPUT_FILE_NAME);
    //write it back out to a different file name
    test.write(fileContents, OUTPUT_FILE_NAME);
  }
  
  /** Read the given binary file, and return its contents as a byte array.*/ 
  byte[] read(String aInputFileName){
    log("Reading in binary file named : " + aInputFileName);
    File file = new File(aInputFileName);
    log("File size: " + file.length());
    byte[] result = new byte[(int)file.length()];
    try {
      InputStream input = null;
      try {
        int totalBytesRead = 0;
        input = new BufferedInputStream(new FileInputStream(file));
        while(totalBytesRead < result.length){
          int bytesRemaining = result.length - totalBytesRead;
          //input.read() returns -1, 0, or more :
          int bytesRead = input.read(result, totalBytesRead, bytesRemaining); 
          if (bytesRead > 0){
            totalBytesRead = totalBytesRead + bytesRead;
          }
        }
        /*
         the above style is a bit tricky: it places bytes into the 'result' array; 
         'result' is an output parameter;
         the while loop usually has a single iteration only.
        */
        log("Num bytes read: " + totalBytesRead);
      }
      finally {
        log("Closing input stream.");
        input.close();
      }
    }
    catch (FileNotFoundException ex) {
      log("File not found.");
    }
    catch (IOException ex) {
      log(ex);
    }
    return result;
  }
  
  /**
   Write a byte array to the given file. 
   Writing binary data is significantly simpler than reading it. 
  */
  void write(byte[] aInput, String aOutputFileName){
    log("Writing binary file...");
    try {
      OutputStream output = null;
      try {
        output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
        output.write(aInput);
      }
      finally {
        output.close();
      }
    }
    catch(FileNotFoundException ex){
      log("File not found.");
    }
    catch(IOException ex){
      log(ex);
    }
  }
  
  /** Read the given binary file, and return its contents as a byte array.*/ 
  byte[] readAlternateImpl(String aInputFileName){
    log("Reading in binary file named : " + aInputFileName);
    File file = new File(aInputFileName);
    log("File size: " + file.length());
    byte[] result = null;
    try {
      InputStream input =  new BufferedInputStream(new FileInputStream(file));
      result = readAndClose(input);
    }
    catch (FileNotFoundException ex){
      log(ex);
    }
    return result;
  }
  
  /**
   Read an input stream, and return it as a byte array.  
   Sometimes the source of bytes is an input stream instead of a file. 
   This implementation closes aInput after it's read.
  */
  byte[] readAndClose(InputStream aInput){
    //carries the data from input to output :    
    byte[] bucket = new byte[32*1024]; 
    ByteArrayOutputStream result = null; 
    try  {
      try {
        //Use buffering? No. Buffering avoids costly access to disk or network;
        //buffering to an in-memory stream makes no sense.
        result = new ByteArrayOutputStream(bucket.length);
        int bytesRead = 0;
        while(bytesRead != -1){
          //aInput.read() returns -1, 0, or more :
          bytesRead = aInput.read(bucket);
          if(bytesRead > 0){
            result.write(bucket, 0, bytesRead);
          }
        }
      }
      finally {
        aInput.close();
        //result.close(); this is a no-operation for ByteArrayOutputStream
      }
    }
    catch (IOException ex){
      log(ex);
    }
    return result.toByteArray();
  }
  
  private static void log(Object aThing){
    System.out.println(String.valueOf(aThing));
  }
} 

Saturday, January 19, 2013

NavigableMap

What is NavigableMap in Java 6 ?
NavigableMap in Java 6 is an extension of SortedMap like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey.it also provide ways to create a Sub Map from existing Map e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between specified toKey and fromKey.These methods also provides a boolean to include specified key or not.

import java.util.NavigableMap;
import java.util.TreeMap;

/**
 *
 * What is NavigableMap in Java. 
 * How to use NavigableMap in Java.
 * NavigableMap provides important features - navigation methods
 * like lowerKey(), floorKey, ceilingKey() and higherKey().
 * There Entry counterpart and methods to create subMap e.g. headMap(), tailMap()
 * and subMap().
 *
 */
public class NavigableMapEx {

    public static void main(String args[]) {
     
        //NavigableMap extends SortedMap to provide useful navigation methods
        NavigableMap navigableMap = new TreeMap();
             
        navigableMap.put("BritneySpears", "I go through life like a karate kid");
        navigableMap.put("AnnePackard", "Nothing happens without risk");
        navigableMap.put("WillSmith", "Life is lived on the edge");
        navigableMap.put("Cinderella", "Live like there is no midnight");
        
        System.out.println("SorteMap:"+ navigableMap);
     
        //lowerKey returns key which is less than specified key
        System.out.println("lowerKey:"+ navigableMap.lowerKey("Cinderella"));
     
        //floorKey returns key which is less than or equal to specified key
        System.out.println("floorKey:"+ navigableMap.floorKey("AnnePackard"));
     
        //ceilingKey returns key which is greater than or equal to specified key
        System.out.println("ceilingKey:"+ navigableMap.ceilingKey("BritneySpears"));
     
        //higherKey returns key which is greater specified key
        System.out.println("higherKey:"+ navigableMap.higherKey("BritneySpears"));
     
     
        //It also provides useful method to create subMap from existing Map 
        //e.g. tailMap, headMap and subMap
     
        //headMap - returns NavigableMap whose key is less than specified
        //param: Key, boolean : inclusive
        NavigableMap headMap = navigableMap.headMap("Cinderella", false);
        System.out.println("headMap created form navigableMap : " + headMap);
             
        //tailMap - returns NavigableMap whose key is greater than specified
        NavigableMap tailMap = navigableMap.tailMap("BritneySpears", false);
        System.out.println("tailMap created form navigableMap : " + tailMap);
     
        //subMap - return NavigableMap from toKey to fromKey
        NavigableMap subMap = 
          navigableMap.subMap("AnnePackard", false,"WillSmith", false);
        System.out.println("subMap created form navigableMap : " + subMap);
    }
}

Friday, January 18, 2013

Nested Static Class

What is nested static class in Java
Nested static class in Java is a static member of any top level class. Though you can make any class static in Java, but you can only make nested classes i.e. class inside another class as static, you can not make any top level class static. Those classes are called nested static classes. Since to create instance of any nested class you require instance of outer class but that is not required in case of static nested class in Java. You can have an instance of nested static class without any instance of outer class. Here is an example of static nested class in Java
public class StaticClass{

    public static void main(String args[]){
        StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
        System.out.println(ns.getDescription());
    }
  
    static class NestedStaticClass{
        public String NestedStaticDescription =" Nested Static Class in Java";
      
        public String getDescription(){
            return NestedStaticDescription;
        }
    }
} 

Output: Example of Nested Static Class in Java

When to use nested static class in Java
Normally we make a class static in Java when we want a single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask when to use Singleton vs Static Class in Java for those purpose,answer is that if its completely stateless and it work on provided data then you can go for static class otherwise Singleton pattern is a better choice.

When to make a method static in Java
We can make a method static in Java in following scenario:
1) Method doesn't depends on object's state, in other words doesn't depend on any member variable and everything they need is passes as parameter to them.
2) Method belongs to class naturally can be made static in Java.
3) Utility methods are good candidate of making static in Java because then they can directly be accessed using class name without even creating any instance. Classic example is java.lang.Math
4) In various designs pattern which need a global access e.g. Singleton pattern, Factory Pattern.

Disadvantage of static method in Java
There are certain disadvantages also if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

Example of static class and method in Java
Static method in Java is very popular to implement Factory design pattern. Since Generics also provides type inference during method invocation, use of static factory method to create object is popular Java idiom. JDK itself is a good example of several static factory methods like String.valueOf(). Core Java library is also a great place to learn how to use static keyword in java with methods, variables and classes. Another popular example of static method is main method in Java.

1. java.util.Collections has some static utility method which operates on provided collection.
2. java.lang.Math class has static method for maths operations.
3. BorderFactory has static method to control creation of object.
4. Singleton Classes like java.lang.Runtime.

Caution : Static methods should not manage or alter any state. and now a funny question what would happen if you execute following code
public class ElectronicSystem {

    private static String category = "electronic system";
    public static void main(String[] args) {
        ElectronicSystem system = null;
        System.out.println(system.category);
    }

will it throw NullPointerException in Java or print "electronic system"

XML

Q: What is XML ?
A : XML stands for Extensible Markup language which means you can extend XML based upon your needs. You can define custom tags like , etc in XML easily as opposed to other mark-up language like HTML where you need to work with predefined tags e.g.

and you can not use user defined tag. Though structure of XML can be standardize by making use of DTD and XML Schema. XML is mostly used to transfer data from one system to another e.g. between client and server in enterprise applications.

Q: Difference between DTD and XML Schema?
A : There are couple of differences between DTD and XML Schema e.g. DTD is not written using XML while XML schema are xml documents in itself, which means existing XML tools like XML parsers can be used to work with XML schema. Also XML schema is designed after DTD and it offer more types to map different types of data in XML documents. On the other hand DTD stands for Document Type definition and was a legacy way to define structure of XML documents.

Q: What is XPath ?
A : XPath is an XML technology which is used to retrieve element from XML documents. Since XML documents are structured, XPath expression can be used to locate and retrieve elements, attributes or value from XML files. XPath is similar to SQL in terms of retrieving data from XML but it has it's own syntax and rules. See here to know more about How to use XPath to retrieve data from XML documents.

Q: What is XSLT?
A : XSLT is another popular XML technology to transform one XML file to other XML, HTML or any other format. XSLT is like a language which specifies its own syntax, functions and operator to transform XML documents. Usually transformation is done by XSLT Engine which reads instruction written using XSLT syntax in XML style sheets or XSL files. XSLT also makes extensive use of recursion to perform transformation. One of the popular example of using XSLT is for displaying data present in XML files as HTML pages. XSLT is also very handy to transforming one XML file into another XML document.

Q: What is element and attribute in XML?
A : This can be best explained by an example. let's see a simple XML snippet

<Orders>
  <Order id="123">
     <Symbol> 6758.T</Symbol>
     <Price> 2300</Price>
  <Order>
<Orders>


In this sample XML id is an attribute of element. Here , and are also other elements but they don't have any attribute.

Q: What is meaning of well formed XML ?
A : Another interesting XML interview question which most appeared in telephonic interviews. A well formed XML means an XML document which is syntactically correct e.g. it has a root element, all open tags are closed properly, attributes are in quotes etc. If an XML is not well formed, it may not be processed and parsed correctly by various XML parsers.

Q: What is XML namespace? Why it's important?
A : XML namespace are similar to package in Java and used to provide a way to avoid conflict between two xml tags of same name but different sources. XML namespace is defined using xmlns attribute at top of the XML document and has following syntax xmlns:prefix="URI". later that prefix is used along with actual tag in XML documents. Here is an example of using XML namespace :

<root xmlns:inst="http://instruments.com/inst">
  <inst:phone>
      <inst:number>837363223</inst:number>
   </inst:phone>
</root>


Q: Difference between DOM and SAX parser ?
A : This is another very popular XML interview question, not just in XML world but also on Java world. Main difference between DOM and SAX parser is the way they parse XML documents. DOM creates an in memory tree representation of XML documents during parsing while SAX is a event driven parser. See Difference between DOM and SAX parser for more detailed answer of this question.

Q: What is a CDATA section in XML?
A : I like this XML Interview questions for its simplicity and importance, yet many programmer doesn't know much about it. CDATA stands for character data and has special instruction for XML parsers. Since XML parser parse all text in XML document e.g. This is name of person here even though value of tag will be parsed because it may contain XML tags e.g. First Name. CDATA section is not parsed by XML parser. CDATA section starts with "".

Q: What is XML data Binding in Java?
A : XML binding in Java refers to creating Java classes and object from XML documents and then modifying XML documents using Java programming language. JAXB , Java API for XML binding provides convenient way to bind XML documents with Java objects. Other alternatives for XML binding is using open source library e.g. XML Beans. One of the biggest advantage of XML binding in Java is to leverage Java programming capability to create and modify XML documents.

Difference between DOM and SAX XML Parser
1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.
2) DOM parser is faster than SAX because it access whole XML document in memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.
4) DOM parser works on Document Object Model while SAX is an event based xml parser.
Ref: javarevisited

Why non-static variable cannot be referenced from a static context?

compiler error: non-static
public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be 
                 //referenced from a static context
    } 
}
Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
In summary since code in static context can be run even without creating any instance of class, it does not make sense asking value for an specific instance which is not yet created.

How to access non static variable inside static method or block
You can still access any non static variable inside any static method or block by creating an instance of class in Java and using that instance to reference instance variable. This is the only legitimate way to access non static variable on static context. here is a code example of accessing non static variable inside static context:
public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
     StaticTest test = new StaticTest(); //accessing static variable by creating 
                                        //an instance of class
     test.count++;
    }  
}

Ref: javarevisited

Thursday, January 17, 2013

NoClassDefFoundError vs ClassNotFoundException

Similarities
1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

Difference
1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.
Ref: javarevisited

What is load-on-startup

load-on-startup is a tag element which appear inside tag in web.xml.

load-on-startup tells the web container about loading of a particular servlet. if you don't specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connections or performing ldap authentication which contribute network latency or any other time consuming job, to avoid this, web container provides you a mean to specify certain servlet to be loaded during deployment time of application by using load-on-startup parameter.

If you specify load-on-startup parameter inside a servlet than based upon its value Container will load it.you can specify any value to this element but in case of load-on-startup>0 , servlet with less number will be loaded first. For example in below web.xml AuthenticationServlet will be loaded before AuthorizationServlet because load-on-startup value for AuthenticationServlet is less (2) while for AuthorizationServlet is 4.

Eg:
<servlet>
<servlet-name>AuthenticationServlet</servlet-name>
<display-name>AuthenticationServlet</display-name>
<servlet-class>com.trading.AuthenticationServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet>
<servlet-name>AuthorizationServlet</servlet-name>
<display-name>AuthorizationServlet</display-name>
<servlet-class>com.trading.AuthorizationServlet</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>

Important points on load-on-startup element
1. If value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
2. if is 0 or negative integer than Servlet will be loaded when Container feels to load them.
3. guarantees loading, initialization and call to init() method of servlet by web container.
4. If there is no element for any servlet than they will be loaded when web container decides to load them.

When to use in web.xml is suitable for those servlet which performs time consuming jobs e.g. Creating Database Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache , clearing pipelines and loading important data in memory. If any of your servlet performs these jobs then declare them using element and specify order as per your business logic or what suites your application. Remember lower the value of , servlet will be loaded first.
Ref: javarevisited

Wednesday, January 16, 2013

POJO

Plain Old Java Object
POJO, or Plain Old Java Object, is a normal Java object class (that is, not a JavaBean, EntityBean etc.) and does not serve any other special role nor does it implement any special interfaces of any of the Java frameworks. This term was coined by Martin Fowler, Rebbecca Parsons and Josh MacKenzie who believed that by creating the acronym POJO, such objects would have a "fancy name", thereby convincing people that they were worthy of use.

Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.

class A {}
class B extends/implements C {}

Note: B is non POJO when C is kind of distributed framework class or ifc. e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn and not serializable/comparable. Since serializable/comparable are valid for POJO.

Here A is simple object which is independent. B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.

Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.

So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.

JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks. It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.

Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.

Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.

Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.

In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model. Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:

Advantages: Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
Ref:stackoverflow

What Is a POJO?

POJO - Plain Old Java Object
A POJO is a Java object that doesn't implement any special interfaces such as those defined by the EJB 2 framework. Martin Fowler, Rebbecca Parsons, and Josh MacKenzie coined the name to give regular Java objects an exciting-sounding name that encouraged developers to use them (www.martinfowler.com/bliki/POJO.html).

To contrast the EJB and POJO approaches consider the following example. Imagine that you worked for a bank and needed to implement a service to transfer money from one bank account to another. If you were using EJB2, your code would most likely consist of a MoneyTransferService stateless session bean that coordinated the transfer of money between the accounts and an Account entity bean that accessed the account data. The problem with this design is that each EJB would be a mixture of business logic and EJB 2 infrastructure code. They would be intimately coupled to the EJB 2 framework. Furthermore, they would be difficult to test without deploying.

By comparison, the POJO version (which is downloadable from www.pojosinaction.com) would look something like Listing 1. The MoneyTransferService and its implementation class define a transfer() method and the Account class maintains a balance and defines debit() and credit() methods. The AccountDAO is the interface for the Data Access Object (DAO) class whose implementation I'll describe later.

As you can see, these are regular Java classes. None of them implement special interfaces or call any framework classes. What's more, the MoneyTransferService doesn't instantiate the AccountDAO directly or look it up using an API such as JNDI. Instead, the AccountDAO is passed as a constructor parameter. This is an example of what is termed dependency injection, which is one of the key enablers for POJO development (www.martinfowler.com/articles/injection.html). In this example, dependency injection decouples the MoneyTransferService from the infrastructure framework. The MoneyTransferService only depends on the AccountDAO interface - not on the framework used to implement the AccountDAO or an API such as JNDI.

You could, of course, simplify the MoneyTransferService by dispensing with the AccountDAO and directly injecting, for example, a Spring HibernateTemplate or an EJB 3 EntityManager. However, I generally prefer to keep my framework-specific data access code separate from my business logic.

The Benefits of POJOs
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. They also simplify development because rather than being forced to think about everything - business logic, persistence, transactions, etc. - at once, you can focus instead on one thing at a time. You can design and implement the business logic and then, once that's working, you can deal with persistence and transactions.

POJOs also accelerate development. You can test your business logic outside of the application server and without a database. You don't have to package your code and deploy it in the application server. You also don't have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish. Tests run in a few seconds and development can happen at the speed of thought - or at least as fast as you can type!
Ref:java.sys-con.com