<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8580915</id><updated>2012-01-27T22:08:19.403+05:30</updated><category term='EJB'/><category term='Java Exceptions'/><category term='Exception'/><title type='text'>JAVA SUCCESS - Articles,Updates,Tips,Faqs</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>12</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8580915.post-4099006404418672745</id><published>2008-08-16T17:56:00.002+05:30</published><updated>2008-08-16T17:59:35.378+05:30</updated><category scheme='http://www.blogger.com/atom/ns#' term='EJB'/><title type='text'>EJB Programming Restrictions</title><content type='html'>In order for the container to properly carry out its duties, provide appropriate services, and manage the components within its environment, a number of restrictions apply to the design and creation of EJBs. These rules often cause much confusion and gnashing of teeth among developers, but it is best to understand and abide by them to avoid problems in your beans and applications. &lt;br /&gt;&lt;br /&gt;"This section describes the programming restrictions that a Bean Provider must follow to ensure that the enterprise bean is portable and can be deployed in any compliant EJB 2.0 Container. The restrictions apply to the implementation of the business methods...&lt;br /&gt;&lt;br /&gt;    * An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.&lt;br /&gt;    * An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances.&lt;br /&gt;    * An enterprise Bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.&lt;br /&gt;    * An enterprise bean must not use the java.io package to attempt to access files and directories in the file system.&lt;br /&gt;    * An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.&lt;br /&gt;    * The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.&lt;br /&gt;    * The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams.&lt;br /&gt;    * The enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.&lt;br /&gt;    * The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread; or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups.&lt;br /&gt;    * The enterprise bean must not attempt to directly read or write a file descriptor.&lt;br /&gt;    * The enterprise bean must not attempt to obtain the security policy information for a particular code source.&lt;br /&gt;    * The enterprise bean must not attempt to load a native library.&lt;br /&gt;    * The enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean.&lt;br /&gt;    * The enterprise bean must not attempt to define a class in a package.&lt;br /&gt;    * The enterprise bean must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity).&lt;br /&gt;    * The enterprise bean must not attempt to use the subclass and object substitution features of the Java Serialization Protocol.&lt;br /&gt;    * The enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject(), SessionContext. getEJBLocalObject(), EntityContext.getEJBObject(), or EntityContext.getEJBLocalObject() instead."&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-4099006404418672745?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/4099006404418672745/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=4099006404418672745&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/4099006404418672745'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/4099006404418672745'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2008/08/ejb-programming-restrictions.html' title='EJB Programming Restrictions'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-5983493125105851695</id><published>2008-05-25T20:29:00.003+05:30</published><updated>2008-06-21T16:25:17.050+05:30</updated><category scheme='http://www.blogger.com/atom/ns#' term='Java Exceptions'/><category scheme='http://www.blogger.com/atom/ns#' term='Exception'/><title type='text'>Enhanced Exception Handling</title><content type='html'>Exception wrapping has a couple of disadvantages&lt;br /&gt;&lt;br /&gt;• Exception wrapping may result in very long stack traces consisting of one stack trace for each exception in the wrapping hierarchy. Most often only the root stack trace is interesting. The rest of the stack traces are then just annoying.&lt;br /&gt;• The messages of the exceptions are spread out over the stack traces. The message of an exception is typically printed above the stack trace. When several exceptions wrap each other in a hierarchy, all these messages are spread out in between the stack traces. This makes it harder to determine what went wrong, and what the program was trying to do when the error happened. In other words, it makes it hard to determine in what context the error occurred. The error might have occurred in a PersonDao class, but was it called from a servlet or from a web service when it failed?&lt;br /&gt;&lt;br /&gt;Exception enhancement is an alternative to Exception wrapping &lt;br /&gt;In exception enhancement we do not wrap exceptions; instead you add contextual information to the original exception and re-throw it. Re-throwing an exception does not reset the stack trace embedded in the exception. &lt;br /&gt;Here is an example:&lt;br /&gt;------------------------------------------------------------------------------------&lt;br /&gt;&lt;code&gt;&lt;br /&gt;public void addItem() throws EnhanceableException{ &lt;br /&gt; try{ &lt;br /&gt;  add(); &lt;br /&gt;      } catch(EnhanceableException e){ &lt;br /&gt;  e.addExceptionMetadata("An error occurred when trying to ..."); &lt;br /&gt;  throw e; &lt;br /&gt;     } &lt;br /&gt;}&lt;br /&gt;public void add() throws EnhanceableException { &lt;br /&gt; if(...) throw new EnhanceableException( "Original error message"); &lt;br /&gt;} &lt;br /&gt;&lt;/code&gt;&lt;br /&gt;---------------------------------------------------------------------------------------&lt;br /&gt;As per the above example we can see the add() method throws an EnhanceableException which is a superclass for Enhanceable exceptions. &lt;br /&gt;NOTE:-&lt;br /&gt;This is not a standard Java exception. So we will have to create it yourself.&lt;br /&gt;In addition to add() method, we also have addItems() method which calls the addExceptionMetadata() method on the caught EnhanceableException, and re-throw it afterwards. As the exception propagates up the call stack, each catch block can add relevant information to the exception if necessary. &lt;br /&gt;Using this simple technique we can only get a single stack trace, and still get any relevant contextual information necessary to investigate the cause of the exception.&lt;br /&gt;&lt;br /&gt;Unique Error Codes&lt;br /&gt;If there is a requirement that each error raised in an application is identified by a unique error code. This can be a bit problematic since some errors are raised inside components that are reused throughout the application. Therefore an exception may seem the same to the component throwing it, but the context in which the exception occurs is different. &lt;br /&gt;&lt;br /&gt;Here is an example:&lt;br /&gt;----------------------------------------------------------------------------------------&lt;br /&gt;&lt;code&gt;&lt;br /&gt;public void addItemService() throws EnhanceableException{ &lt;br /&gt; try{ &lt;br /&gt;  add(); &lt;br /&gt;       } catch(EnhanceableException e){&lt;br /&gt;   e.addExceptionMetadata("An error occurred when trying to ..."); throw e; &lt;br /&gt;       } &lt;br /&gt;} &lt;br /&gt;public void addItem() throws EnhanceableException{ &lt;br /&gt; try{ &lt;br /&gt;  add(); &lt;br /&gt;     } catch(EnhanceableException e){ &lt;br /&gt;  e.addExceptionMetadata("An error occurred when trying to ..."); throw e; &lt;br /&gt;     } &lt;br /&gt;} &lt;br /&gt;public void add() throws EnhanceableException { &lt;br /&gt; if(...) throw new EnhanceableException( "ERROR1", "Original error message"); } &lt;br /&gt;&lt;/code&gt;&lt;br /&gt;----------------------------------------------------------------------------------------------------&lt;br /&gt;In the above example we have add() method which adds the code "ERROR1" to the thrown EnhanceableException to uniquely identify that error cause. &lt;br /&gt;But, notice too that add() method is called from both addItem() and addItemService() methods. &lt;br /&gt;Though the error may seem the same to add() method no matter which of addItem() and addItemServce() method that called it, this may important to know for the developer investigating the error. The error code "ERROR1" is enough to determine where the error occurred, but not in what context it occurred. &lt;br /&gt;A solution to this problem is to add unique context error codes to the exception the same way the other contextual information is added. Here is an example where we modify the addExceptionMetadata() method has been changed to accommodate this: &lt;br /&gt;---------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;code&gt;&lt;br /&gt;public void addItemService() throws EnhanceableException{ &lt;br /&gt; try{ &lt;br /&gt;  add(); &lt;br /&gt;      } catch(EnhanceableException e){ &lt;br /&gt;e.addExceptionMetadata("addItemService", "ERROR1", "An error occurred when trying to ..."); throw e; &lt;br /&gt;      } &lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public void addItem() throws EnhanceableException{ &lt;br /&gt; try{ &lt;br /&gt;  add(); &lt;br /&gt;      } catch(EnhanceableException e){&lt;br /&gt;e.addExceptionMetadata("addItem", "ERROR1", "An error occurred when trying to ..."); throw e; &lt;br /&gt;      } &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;public void add() throws EnhanceableException { &lt;br /&gt; if (---){&lt;br /&gt; throw new EnhanceableException( "add", "ERROR1", &lt;br /&gt;"Original error message"); &lt;br /&gt;           }&lt;br /&gt;} &lt;br /&gt;&lt;/code&gt;&lt;br /&gt;--------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;We can add two new parameters to the addExceptionMetadata() method and the constructor of the EnhanceableException. &lt;br /&gt;• The first parameter is a code identifying the context in which the error occurred. &lt;br /&gt;• The second parameter is a unique error code within that context. &lt;br /&gt;An error identification for an exception thrown by add() method when called from addItem() method will now look like this: &lt;br /&gt;[addItem:ERROR1][add:ERROR1] &lt;br /&gt;And error identification for an exception thrown by add() method when called from addItemService() method will now look like this: &lt;br /&gt;[addMethodService:ERROR1][add:ERROR1] &lt;br /&gt;Now it is possible to distinguish an exception thrown from add()  method via addItem() method from the same exception thrown from add() method via addItemservice() method.  &lt;br /&gt;NOTE:- &lt;br /&gt;This is only required if we have a Requirement where we need to have extra Contextual Error code.&lt;br /&gt; &lt;br /&gt;Wrapping Non-Enhanceable Exceptions&lt;br /&gt;We may not always be able to avoid exception wrapping. If a component in our application throws a checked exception that is not Enhanceable, we may have to wrap it in an Enhanceable exception. Here is an example where add() method catches a non-Enhanceable exception and wraps it in an Enhanceable exception, and throws the Enhanceable exception: &lt;br /&gt;&lt;code&gt;&lt;br /&gt;public void method1() throws EnhanceableException { &lt;br /&gt; try{ &lt;br /&gt;  ... call some method that throws an IOException ... &lt;br /&gt;      } catch(IOException ioexception) {&lt;br /&gt;throw new EnhanceableException( ioexception, "METHOD1", "ERROR1", "Original error message"); &lt;br /&gt;      }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Unchecked EnhanceableException&lt;br /&gt;After reading the below article, It should be a good idea to have EnhanceableException as unchecked, by having it extend RuntimeException.&lt;br /&gt;Refer below link&lt;br /&gt;Would You Like Checked or Unchecked Exceptions With That?&lt;br /&gt;Exception Enhancement and Pluggable Exception Handlers&lt;br /&gt;Like with any other exception type it is possible to use pluggable exception handlers with Enhanceable exceptions. If we use the unique error codes described earlier these codes must be added as paremeters to the exception handler interface. Here is an example exception handler interface supporting these unique error codes: &lt;br /&gt;&lt;code&gt;&lt;br /&gt;public interface ExceptionHandler{&lt;br /&gt;&lt;br /&gt;   public void handle(String contextCode, String errorCode,&lt;br /&gt;                      String errorText, Throwable t)&lt;br /&gt;&lt;br /&gt;   public void raise(String contextCode, String errorCode,&lt;br /&gt;                     String errorText);&lt;br /&gt;   &lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Exceptions caught in the program will be passed to the handleException() which will decide what concrete exception to throw instead. In this case an EnhanceableException is thrown. If the EnhanceableException is unchecked it is not necessary to declare it in the handleException() method. &lt;br /&gt;&lt;br /&gt;An Example EnhanceableException&lt;br /&gt;Below is an example of an Enhanceable exception that we can use as a template or create our own Enhanceable exceptions based on this template. &lt;br /&gt;The class definition can be modified to suit the requirements. The exception is designed to use unique error codes as described earlier. &lt;br /&gt;Below the code is an example application that uses the EnhanceableException, and a stack trace generated from this application. &lt;br /&gt;&lt;br /&gt;ExceptionMetadata class&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/** This class would be used for keeping the Exception information **/&lt;br /&gt;protected class ExceptionMetadata{&lt;br /&gt;        public String errorContext = null;&lt;br /&gt;        public String errorCode  = null;&lt;br /&gt;        public String errorText  = null;&lt;br /&gt;        public ExceptionMetadata(String contextCode, String errorCode,&lt;br /&gt;                                     String errorText){&lt;br /&gt;&lt;br /&gt;            this.errorContext = contextCode;&lt;br /&gt;            this.errorCode   = errorCode;&lt;br /&gt;            this.errorText   = errorText;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;ExceptionHandler Class&lt;br /&gt;public class ExceptionHandler{&lt;br /&gt; public void handle(String errorContext, String errorCode,&lt;br /&gt;                           String errorText, Throwable t){&lt;br /&gt;&lt;br /&gt;            if(! (t instanceof EnhanceableException)){&lt;br /&gt;                throw new EnhanceableException(&lt;br /&gt;                    errorContext, errorCode, errorText, t);&lt;br /&gt;            } else {&lt;br /&gt;                ((EnhanceableException) t).addExceptionMetadata(&lt;br /&gt;                    errorContext, errorCode, errorText);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void raise(String errorContext, String errorCode,&lt;br /&gt;                          String errorText){&lt;br /&gt;            throw new EnhanceableException(&lt;br /&gt;                errorContext, errorCode, errorText);&lt;br /&gt;        }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;EnhanceableException Class&lt;br /&gt;&lt;br /&gt;import java.util.ArrayList;&lt;br /&gt;import java.util.List;&lt;br /&gt;&lt;br /&gt;public class EnhanceableException extends RuntimeException {&lt;br /&gt;    public static final long serialVersionUID = -1;&lt;br /&gt;&lt;br /&gt;    protected List&lt;ExceptionMetadata&gt; exceptionMetadatas =&lt;br /&gt;            new ArrayList&lt;ExceptionMetadata&gt;();&lt;br /&gt;&lt;br /&gt;    public EnhanceableException(String errorContext, String errorCode,&lt;br /&gt;                               String errorMessage){&lt;br /&gt;        addExceptionMetadata(errorContext, errorCode, errorMessage);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public EnhanceableException(String errorContext, String errorCode,&lt;br /&gt;                               String errorMessage, Throwable cause){&lt;br /&gt;        super(cause);&lt;br /&gt;        addExceptionMetadata(errorContext, errorCode, errorMessage);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public EnhanceableException addExceptionMetadata(&lt;br /&gt;        String errorContext, String errorCode, String errorText){&lt;br /&gt;        this.exceptionMetadatas.add(&lt;br /&gt;            new ExceptionMetadata(errorContext, errorCode, errorText));&lt;br /&gt;        return this;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //This create the String consisting of all the contextual error&lt;br /&gt; // codes&lt;br /&gt;    public String getCode(){&lt;br /&gt;        StringBuilder builder = new StringBuilder();&lt;br /&gt;&lt;br /&gt; //Iterating over the exception meta data info list&lt;br /&gt;        for(int i = this.exceptionMetadatas.size()-1 ; i &gt;=0; i--){&lt;br /&gt;ExceptionMetadata exceptionMetadata = this.ExceptionMetadatas.get(i);&lt;br /&gt;            builder.append('[');&lt;br /&gt;            builder.append(exceptionMetadata.errorContext);&lt;br /&gt;            builder.append(':');&lt;br /&gt;            builder.append(exceptionMetadata.errorCode);&lt;br /&gt;            builder.append(']');&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return builder.toString();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String toString(){&lt;br /&gt;        StringBuilder builder = new StringBuilder();&lt;br /&gt;&lt;br /&gt;        builder.append(getCode());&lt;br /&gt;        builder.append('\n');&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        //append additional context infomation&lt;br /&gt;        for(int i = this.exceptionMetadatas.size()-1 ; i &gt;=0; i--){&lt;br /&gt;            ExceptionMetadata exceptionMetadata = this.ExceptionMetadatas.get(i);&lt;br /&gt;            builder.append('[');&lt;br /&gt;            builder.append(exceptionMetadata.errorContext);&lt;br /&gt;            builder.append(':');&lt;br /&gt;            builder.append(exceptionMetadata.errorCode);&lt;br /&gt;            builder.append(']');&lt;br /&gt;            builder.append(exceptionMetadata.errorText);&lt;br /&gt;            if(i&gt;0) builder.append('\n');&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        //append root causes and text from this exception first.&lt;br /&gt;        if(getMessage() != null) {&lt;br /&gt;            builder.append('\n');&lt;br /&gt;            if(getCause() == null){&lt;br /&gt;                builder.append(getMessage());&lt;br /&gt;            } else if(!getMessage().equals(getCause().toString())){&lt;br /&gt;                builder.append(getMessage());&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        appendException(builder, getCause());&lt;br /&gt;&lt;br /&gt;        return builder.toString();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void appendException(&lt;br /&gt;            StringBuilder builder, Throwable throwable){&lt;br /&gt;        if(throwable == null) return;&lt;br /&gt;        appendException(builder, throwable.getCause());&lt;br /&gt;        builder.append(throwable.toString());&lt;br /&gt;        builder.append('\n');&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Here Is the Test Class for EnhanceableException&lt;br /&gt;&lt;code&gt;&lt;br /&gt;public class ExceptionTest {&lt;br /&gt; &lt;br /&gt;    protected ExceptionHandler exceptionHandler = new ExceptionHandler();&lt;br /&gt;&lt;br /&gt;    public static void main(String[] args){&lt;br /&gt;        ExceptionTest test = new ExceptionTest();&lt;br /&gt;        try{&lt;br /&gt;            test.method1();&lt;br /&gt;        } catch(Exception e){&lt;br /&gt;            e.printStackTrace();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void method1(){&lt;br /&gt;        try{&lt;br /&gt;            method2();&lt;br /&gt;        } catch (EnhanceableException e){&lt;br /&gt;            this.exceptionHandler.handle(&lt;br /&gt;                "M1", "E1", "Error in method 1, calling method 2", e);&lt;br /&gt;            throw e;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void method2(){&lt;br /&gt;        try{&lt;br /&gt;            method3();&lt;br /&gt;        } catch (EnhanceableException e){&lt;br /&gt;            this.exceptionHandler.handle(&lt;br /&gt;                "M2", "E2", "Error in method 2, calling method 3", e);&lt;br /&gt;            throw e;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void method3(){&lt;br /&gt;        try{&lt;br /&gt;            method4();&lt;br /&gt;        } catch(Exception e){&lt;br /&gt;            this.exceptionHandler.handle(&lt;br /&gt;                "M3", "E3", "Error at method 3", e);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void method4(){&lt;br /&gt;        throw new IllegalArgumentException("incorrect argument passed");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Test Case Output:-&lt;br /&gt;&lt;br /&gt;[M1:E1][M2:E2][M3:E3]&lt;br /&gt;[M1:E1]Error in method 1, calling method 2&lt;br /&gt;[M2:E2]Error in method 2, calling method 3&lt;br /&gt;[M3:E3]Error at method 3&lt;br /&gt;java.lang.IllegalArgumentException: incorrect argument passed&lt;br /&gt;&lt;br /&gt; at exception.ExceptionTest$1.handle(ExceptionTest.java:8)&lt;br /&gt; at exception.ExceptionTest.method3(ExceptionTest.java:49)&lt;br /&gt; at exception.ExceptionTest.method2(ExceptionTest.java:38)&lt;br /&gt; at exception.ExceptionTest.method1(ExceptionTest.java:29)&lt;br /&gt; at exception.ExceptionTest.main(ExceptionTest.java:21)&lt;br /&gt;Caused by: java.lang.IllegalArgumentException: incorrect argument passed&lt;br /&gt; at exception.ExceptionTest.method4(ExceptionTest.java:54)&lt;br /&gt; at exception.ExceptionTest.method3(ExceptionTest.java:47)&lt;br /&gt; ... 3 more&lt;br /&gt;&lt;br /&gt;That all !!!&lt;br /&gt;&lt;br /&gt;If you want to read more on Java Exception, below are some good links&lt;br /&gt;http://dev2dev.bea.com/lpt/a/541&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-5983493125105851695?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/5983493125105851695/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=5983493125105851695&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/5983493125105851695'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/5983493125105851695'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2008/05/enhanced-exception-handling.html' title='Enhanced Exception Handling'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-117568024351478544</id><published>2007-04-04T15:19:00.000+05:30</published><updated>2007-04-04T15:20:43.526+05:30</updated><title type='text'>SimpleBlowfish encryption code</title><content type='html'>import base64.Base64;&lt;br /&gt;&lt;br /&gt;import javax.crypto.NoSuchPaddingException;&lt;br /&gt;import javax.crypto.BadPaddingException;&lt;br /&gt;import javax.crypto.IllegalBlockSizeException;&lt;br /&gt;import javax.crypto.Cipher;&lt;br /&gt;import javax.crypto.spec.SecretKeySpec;&lt;br /&gt;import java.security.NoSuchAlgorithmException;&lt;br /&gt;import java.security.InvalidKeyException;&lt;br /&gt;import java.io.UnsupportedEncodingException;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * This class implements a brain-dead-simple BLowfish encryption and decryption scheme.  Don't use this if you want "real"&lt;br /&gt; * security, but when ROT13's just a leeeetle lightweight.  Consider the results opaque--that is, don't attempt to take&lt;br /&gt; * the results from the encrypt step and decrypt it using anything but the decrypt step here.&lt;br /&gt; */&lt;br /&gt;public class SimpleBlowfish {&lt;br /&gt;&lt;br /&gt;            private static final String pk = "ah90y34n0a";&lt;br /&gt;            private static final String ALGORITHM = "Blowfish";&lt;br /&gt;            private static final String STRING_ENCODING = "UTF-8";&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            /**&lt;br /&gt;             * Encrypts and encodes the secret using the default encryption key.  The encoded result is base64, thus safe as 7-bit ASCII.&lt;br /&gt;             * @param secret&lt;br /&gt;             * @return&lt;br /&gt;             * @throws BadPaddingException&lt;br /&gt;             * @throws NoSuchAlgorithmException&lt;br /&gt;             * @throws IllegalBlockSizeException&lt;br /&gt;             * @throws UnsupportedEncodingException&lt;br /&gt;             * @throws InvalidKeyException&lt;br /&gt;             * @throws NoSuchPaddingException&lt;br /&gt;             */&lt;br /&gt;            public static String encryptAndEncode(String secret) throws BadPaddingException, NoSuchAlgorithmException,&lt;br /&gt;                                    IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException, NoSuchPaddingException&lt;br /&gt;            {&lt;br /&gt;                return encryptAndEncode(secret, pk);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            /**&lt;br /&gt;             * Encrypts and encodes the secret using the given encryptionKey.  The encoded result is base64, thus safe as 7-bit ASCII.&lt;br /&gt;             * @param secret&lt;br /&gt;             * @param encryptionKey&lt;br /&gt;             * @return&lt;br /&gt;             * @throws NoSuchPaddingException&lt;br /&gt;             * @throws NoSuchAlgorithmException&lt;br /&gt;             * @throws InvalidKeyException&lt;br /&gt;             * @throws BadPaddingException&lt;br /&gt;             * @throws IllegalBlockSizeException&lt;br /&gt;             * @throws UnsupportedEncodingException&lt;br /&gt;             */&lt;br /&gt;            public static String encryptAndEncode(String secret, String encryptionKey)&lt;br /&gt;                                    throws NoSuchPaddingException, NoSuchAlgorithmException,&lt;br /&gt;                                    InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException&lt;br /&gt;            {&lt;br /&gt;                        byte[] kbytes = encryptionKey.getBytes(STRING_ENCODING);&lt;br /&gt;                        SecretKeySpec key = new SecretKeySpec(kbytes, ALGORITHM);&lt;br /&gt;                        Cipher cipher = Cipher.getInstance(ALGORITHM);&lt;br /&gt;                        cipher.init(Cipher.ENCRYPT_MODE, key);&lt;br /&gt;&lt;br /&gt;                        byte[] secretBytes = secret.getBytes(STRING_ENCODING);&lt;br /&gt;                        byte[] secretEncryptedBytes = cipher.doFinal(secretBytes);&lt;br /&gt;                        String secretEncryptedAndEncoded = Base64.encodeBytes(secretEncryptedBytes);&lt;br /&gt;                        return secretEncryptedAndEncoded;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            /**&lt;br /&gt;             * Decode and decrypts a secret encrypted and encoded by one of the two encrypt-and-encode methods above.&lt;br /&gt;             * @param secretEncryptedAndEncoded&lt;br /&gt;             * @return&lt;br /&gt;             * @throws BadPaddingException&lt;br /&gt;             * @throws NoSuchAlgorithmException&lt;br /&gt;             * @throws IllegalBlockSizeException&lt;br /&gt;             * @throws UnsupportedEncodingException&lt;br /&gt;             * @throws InvalidKeyException&lt;br /&gt;             * @throws NoSuchPaddingException&lt;br /&gt;             */&lt;br /&gt;            public static char[] decodeAndDecrypt(String secretEncryptedAndEncoded) throws BadPaddingException, NoSuchAlgorithmException,&lt;br /&gt;                                    IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException, NoSuchPaddingException&lt;br /&gt;            {&lt;br /&gt;                return decodeAndDecrypt(secretEncryptedAndEncoded, pk);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            /**&lt;br /&gt;             * Decode and decrypts a secret encrypted and encoded by one of the two encrypt-and-encode methods above.&lt;br /&gt;             * @param secretEncryptedAndEncoded&lt;br /&gt;             * @param encryptionKey&lt;br /&gt;             * @return&lt;br /&gt;             * @throws NoSuchPaddingException&lt;br /&gt;             * @throws NoSuchAlgorithmException&lt;br /&gt;             * @throws InvalidKeyException&lt;br /&gt;             * @throws BadPaddingException&lt;br /&gt;             * @throws IllegalBlockSizeException&lt;br /&gt;             * @throws UnsupportedEncodingException&lt;br /&gt;             */&lt;br /&gt;            public static char[] decodeAndDecrypt(String secretEncryptedAndEncoded, String encryptionKey)&lt;br /&gt;                                    throws NoSuchPaddingException, NoSuchAlgorithmException,&lt;br /&gt;                                    InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException&lt;br /&gt;            {&lt;br /&gt;                        byte[] kbytes = encryptionKey.getBytes(STRING_ENCODING);&lt;br /&gt;                        SecretKeySpec key = new SecretKeySpec(kbytes, ALGORITHM);&lt;br /&gt;                        Cipher cipher = Cipher.getInstance(ALGORITHM);&lt;br /&gt;                        cipher.init(Cipher.DECRYPT_MODE, key);&lt;br /&gt;&lt;br /&gt;                        byte[] secretEncryptedBytes = Base64.decode(secretEncryptedAndEncoded);&lt;br /&gt;                        byte[] secretBytes = cipher.doFinal(secretEncryptedBytes);&lt;br /&gt;                        String secret = new String(secretBytes,STRING_ENCODING);&lt;br /&gt;                        char[] secretChars = secret.toCharArray();&lt;br /&gt;                        return secretChars;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            public static void main(String[] args) throws NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException, NoSuchPaddingException {&lt;br /&gt;                        System.out.println("encryptAndEncode(\"marty\") = " + encryptAndEncode("marty"));&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-117568024351478544?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/117568024351478544/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=117568024351478544&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/117568024351478544'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/117568024351478544'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2007/04/simpleblowfish-encryption-code.html' title='SimpleBlowfish encryption code'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-110508387361420801</id><published>2005-01-07T13:13:00.000+05:30</published><updated>2005-01-07T13:14:33.613+05:30</updated><title type='text'>How do I convert a numeric IP address like 199.1.32.90 into a hostname like star.blackstar.com?</title><content type='html'>String hostname = InetAddress.getByName("199.1.32.90").getHostName()&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-110508387361420801?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/110508387361420801/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=110508387361420801&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/110508387361420801'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/110508387361420801'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2005/01/how-do-i-convert-numeric-ip-address.html' title='How do I convert a numeric IP address like 199.1.32.90 into a hostname like star.blackstar.com?'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-110508368106945838</id><published>2005-01-07T13:08:00.000+05:30</published><updated>2005-01-07T13:11:21.070+05:30</updated><title type='text'>Does Java have pointers?</title><content type='html'>No, no, a thousand times no. Java does not have pointers, no way, no how.&lt;br /&gt;Java does have references. A reference is an abstract identifier for an object. It is not a pointer. A reference tags a particular object with a name in the Java virtual machine so that the programmer may refer to it. How exactly the virtual machine implements references at the level of machine code is VM-dependent and completely hidden from the programmer in any case. Most VMs including Sun's use handles, not pointers. A handle is a pointer to a pointer. At the level of machine code in the CPU a reference is an address in memory where the address of the object is stored. This way the objects can be moved around in memory and only the master pointer needs to be updated rather than all references to the object. This is completely hidden from the Java programmer, though. Only the implementer of the virtual machine needs to worry about it. Indeed, this is not the only way references can be implemented. Microsoft's VM actually does use pointers rather than handles. Other schemes are possible. &lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-110508368106945838?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/110508368106945838/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=110508368106945838&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/110508368106945838'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/110508368106945838'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2005/01/does-java-have-pointers.html' title='Does Java have pointers?'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109833623975270790</id><published>2004-10-21T10:53:00.000+05:30</published><updated>2004-10-21T10:53:59.753+05:30</updated><title type='text'>Code For Using DecimalFormat</title><content type='html'>public String getCreditAmountFormat() {&lt;br /&gt;     DecimalFormat df = new DecimalFormat("00000000000000,000");&lt;br /&gt;     df.setMinimumIntegerDigits(14);&lt;br /&gt;     df.setMinimumFractionDigits(3);&lt;br /&gt;     df.setGroupingUsed(false);&lt;br /&gt;     DecimalFormatSymbols dfs = new DecimalFormatSymbols();&lt;br /&gt;     dfs.setDecimalSeparator(',');&lt;br /&gt;     df.setDecimalFormatSymbols(dfs);&lt;br /&gt;     return df.format(creditAmount.doubleValue());&lt;br /&gt;}&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109833623975270790?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109833623975270790/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109833623975270790&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109833623975270790'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109833623975270790'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/code-for-using-decimalformat.html' title='Code For Using DecimalFormat'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109721978841794590</id><published>2004-10-08T13:45:00.000+05:30</published><updated>2004-10-08T12:51:49.393+05:30</updated><title type='text'>Java 5 features</title><content type='html'>The new features in Java 5 can roughly be organized into four categories: enhanced language features, Virtual Machine upgrades, library updates, and desktop (UI) enhancements. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Language Features &lt;/strong&gt;&lt;br /&gt;There is a long list of language features that could be mentioned, but we will only take time to address some of the most significant developments. &lt;br /&gt;Enumerated types – An enumerated type is a datatype containing a fixed set of constant values. As implemented in J2SE 5.0, enums are object-oriented (users can define methods and fields) and typesafe.&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Formatted I/O&lt;/strong&gt; – Console output has been enhanced by implementing printf-style formatters, enabling many legacy C applications to be ported without changing the expected output format. On the input side of the house, the Scanner API has been provided to offer developers a more robust mechanism for reading in data types rather than simply parsing strings from buffered System.in calls.&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Generic types&lt;/strong&gt; – Perhaps the most significant enhancements made to the Java language revolve around the introduction of generic types. Gone are the days when Java developers must toil and sweat to cast objects up and down the type hierarchy. With generic types, a collection’s type can be specified at compile time to permit compile type checks and ease development by providing implicit type casting. Additionally, primitive types are now able to automatically convert (autoboxing/unboxing) between the primitive type and its corresponding Object wrapper (int &lt;----&gt; Integer, boolean &lt;----&gt; Boolean, char &lt;----&gt; Char, etc.).&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Metadata &lt;/strong&gt;– J2SE 5.0 now supports the inclusion of metadata related to Java classes, interfaces, fields, and methods. Development tools are the intended consumers for this metadata to support the automated insertion of additional source code, debugging functionality, and creation/modification of external XML files or configuration files to support application runtime and deployment.&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Varargs&lt;/strong&gt; – With J2SE 5.0, support for passing a variable number of arguments into a method has been added. By using a special notation (…) in the method signature’s parameter list, an ad hoc Object array can be created. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Java Library&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;There are two new Java libraries, and a host of updates to existing Java libraries. The new libraries are the Java Concurrency Utilities (JSR-166) which provide advanced multithreading controls, and the JVM Profiling API (JSR-163), which is a more powerful native profiling API called JVMTI. &lt;br /&gt;The concurrency utilities provide advanced, high-level multithreading capabilities such as thread-safe queues, a thread task framework through executors, locks (including semaphores), timers, and various other synchronization primitives. For more details, explore the JavaDocs under java.lang.concurrent. &lt;br /&gt;The JVMTI implementation includes Java Programming Language Instrumentation Services (JPLIS) which function at the bytecode level to enable analysis tools to add profiling, monitoring, and debugging where it is needed. This technique provides great flexibility and limits the interference of profiling and monitoring tools on a currently executing JVM. For more details, explore the JavaDocs under java.lang.instrument. A wide range of other existing Java libraries have received important updates, including the Utility package, Networking, Security, RMI, JDBC, and the CORBA libraries. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Desktop (UI)&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;J2SE 5.0 has taken some significant strides to address the traditionally slow startup time and heavy-weight memory footprint that has traditionally plagued Java desktop applications. The new version boasts enhanced font capabilities (especially to support localization and internationalization), many updates to Java Sound (broader platform support, optimized direct audio access, an improved and real-time Sequencer, etc.), hardware-accelerated rendering for Java 2D using OpenGL drivers, and even a new skin changing look and feel (Synth) and Theme (Ocean) for Swing. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Virtual Machine&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Error Handling&lt;/strong&gt; – Although the improvements are simple, the value is tremendous. Java developers now have the ability to capture stack traces as String objects and use them however they need to using the getStackTrace and Thread.getAllStackTraces, rather than being forced to send Stack Trace information to the console. Additionally, the HotSpot JVM has been updated to include a fatal error handler for running a user-supplied script or program if the JVM dies. Finally, the HotSpot JVM has been given a serviceability agent connector that permits monitoring and debugging tools to connect to a hung JVM or core file and extract relevant diagnostic data. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Management and Monitoring&lt;/strong&gt; – From instrumentation (JPLIS) to Java Management Extensions (JMX) support, to support of remote access protocols and SNMP tools, management and monitoring have been greatly enhanced with J2SE 5.0. All of this is ready to use out of the box, supporting local and remote management and monitoring of a running JVM.&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Performance and Scalability&lt;/strong&gt; – A great deal of attention has been given to the subject of performance in this latest release of the core Java platform. Java 5 starts more quickly, leaves a smaller memory footprint, and offers enhanced scalability by enabling multiple JVMs to share read-only data. One really interesting enhancement is the ability to designate the role of a JVM as either a ‘client’ or a ‘server’. The JVM then automatically tunes itself to provide the optimum environment for the specified role, delivering enhanced performance, garbage collection, and thread prioritization. &lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Analysis of Java 5&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Overall, J2SE 5.0 has really aimed to make developing Java software easier. From language features that save time and effort (generics, formatted I/O, metadata, varargs, etc.), to enhanced error handling, JVM management, performance and scalability, and many Java library updates to ease common developer headaches. &lt;br /&gt;With the inclusion of generics, overhauled JVM, and emphasis upon performance and scalability of the platform, the Sun engineering team addressed all the major items on my list of desired improvements to the Java platform. The only other thing that I really wished I had seen with this release was an enhanced Java Reference API to support more object-oriented caching capabilities within the platform straight out of the box (rather than relying upon this value-add from external vendors).&lt;br /&gt; &lt;br /&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Java has come a long way over the past nine years. The strides made in this new release of the Java platform will no doubt be significant for the viability of the platform. It is critical that Sun shows the industry that Java is still an innovative platform that is robust enough and flexible enough to meet the ever-changing climate of the Information Technology sector. If the industry takes a close look at Java 5, I believe they will see that this is, in fact, the case. Go Tiger – 1, 2, …5!&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109721978841794590?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109721978841794590/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109721978841794590&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109721978841794590'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109721978841794590'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/java-5-features.html' title='Java 5 features'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109721573426617237</id><published>2004-10-08T11:37:00.000+05:30</published><updated>2004-10-08T11:42:07.130+05:30</updated><title type='text'>Taming Tiger: Formatted output - Let there be printf</title><content type='html'>The original plan for the 1.4 release J2SE included support for formatted output. Probably due to time constraints and the fact that the feature wasn't a release driver, the capabilities were left out of the release. Now with Tiger, there is built in support for printing with format strings. &lt;br /&gt;&lt;br /&gt;For those who grew up with Java programming and never touched C or those who haven't lived in a C world for some time, format strings are those funky text strings that specify output characteristics for a bunch of variables. Instead of just concatenating strings together with the plus sign (as in firstName + " " + lastName), you provide a single string to describe the output and provide the arguments to fill the placeholders in that string at the end of the method call: String s = String.format("%1$s %2$s", firstName, lastName). &lt;br /&gt;&lt;br /&gt;Formatter class&lt;br /&gt;First, let's look at the new java.util.Formatter class. You probably won't use this class directly much, but it provides the guts for the formatting you'll be doing. In the Javadoc for this class, you'll find a table describing the supported formatting options. These options range from something like %7.4f for specifying the precision and width of a floating point number to %tT for formatting a time to %3$s for formatting the third argument. &lt;br /&gt;&lt;br /&gt;Using Formatter to format output involves two steps: creating an Appendable object to store the output and using the format() method to put formatted content into that object. Here's a list of implementers for the Appendable interface: &lt;br /&gt;&lt;br /&gt;BufferedWriter &lt;br /&gt;CharArrayWriter &lt;br /&gt;CharBuffer &lt;br /&gt;FileWriter &lt;br /&gt;FilterWriter &lt;br /&gt;LogStream &lt;br /&gt;OutputStreamWriter &lt;br /&gt;PipedWriter &lt;br /&gt;PrintStream &lt;br /&gt;PrintWriter &lt;br /&gt;StringBuffer &lt;br /&gt;StringBuilder &lt;br /&gt;StringWriter &lt;br /&gt;Writer &lt;br /&gt;An object implementing this interface can be used as the destination when using a Formatter class by passing the object into the Formatter constructor. Most of these classes should look familiar, except for the StringBuilder class. StringBuilder is nearly identical to the StringBuffer class, with one big exception: It isn't thread safe. If you know you are going to build up a string in a single thread, use StringBuilder. If the building can cross thread bounds, use StringBuffer. Listing 1 shows how you'd typically start using Formatter: &lt;br /&gt;&lt;br /&gt;Listing 1. Typical formatter usage&lt;br /&gt;&lt;br /&gt;   StringBuilder sb = new StringBuilder();&lt;br /&gt;   Formatter formatter = new Formatter(sb, Locale.US);&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;After creating a Formatter class, you call its format() method with format strings and arguments. If you need to use a different Locale than that sent into the constructor for part of the formatted output, you can also pass in a Locale object to the format() method. Listing 2 shows the two varieties of format(): &lt;br /&gt;&lt;br /&gt;Listing 2. format() methods of Formatter&lt;br /&gt;&lt;br /&gt;public Formatter format(String format,&lt;br /&gt;                        Object... args)&lt;br /&gt;public Formatter format(Locale l,&lt;br /&gt;                        String format,&lt;br /&gt;                        Object... args)&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;If you want to get the value of Pi to 10 digits of precision, the code in Listing 3 will put that value into the StringBuilder and print the output. Printing the formatter object will display the content of the Appendable object. &lt;br /&gt;&lt;br /&gt;Listing 3. Demonstrating a Formatter&lt;br /&gt;&lt;br /&gt;import java.util.Locale;&lt;br /&gt;import java.util.Formatter;&lt;br /&gt;&lt;br /&gt;public class Build {&lt;br /&gt;  public static void main(String args[]) {&lt;br /&gt;   StringBuilder sb = new StringBuilder();&lt;br /&gt;   Formatter formatter = new Formatter(sb, Locale.US);&lt;br /&gt;   formatter.format("PI = %12.10f", Math.PI);&lt;br /&gt;   System.out.println(formatter);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;Don't forget to compile with the -source 1.5 option or the compiler won't recognize the variable argument list. Because formatting output and sending it to the console are common tasks, there are conveniences available to this behavior. We'll look at those next. &lt;br /&gt;&lt;br /&gt;PrintStream support&lt;br /&gt;The PrintStream class contains the definition of the common System.out and System.err objects for writing to standard output and standard error, respectively. Introduced in Tiger are two new constructors (for going straight to a file) and six methods for formatting support (three sets of pairs). The first pair is different versions of the append() method. This pair implements the new java.lang.Appendable interface. You would typically not call these methods directly. The ones you would call directly are format() and printf(), where the printf() versions are just convenience wrappers for the format() versions, as shown in Listing 4: &lt;br /&gt;&lt;br /&gt;Listing 4. PrintStream.format methods&lt;br /&gt;&lt;br /&gt;public PrintStream format(String format,&lt;br /&gt;                          Object... args) &lt;br /&gt;public PrintStream format(Locale l,&lt;br /&gt;                          String format,&lt;br /&gt;                          Object... args) &lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;Keep in mind the new variable argument support, which is designated by the ... shown in Listing 4 above. &lt;br /&gt;&lt;br /&gt;Listing 5 demonstrates the use of the format() method of PrintStream to print today's date: &lt;br /&gt;&lt;br /&gt;Listing 5. Example PrintStream.format usage&lt;br /&gt;/&lt;br /&gt;import java.util.Calendar;&lt;br /&gt;&lt;br /&gt;public class Now {&lt;br /&gt;  public static void main(String args[]) {&lt;br /&gt;    System.out.format(&lt;br /&gt;        "Today is %1$tB %1$te, %1$tY.",&lt;br /&gt;        Calendar.getInstance()&lt;br /&gt;        );&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;The output from running this program is Today is April 2, 2004., although the actual output depends on the date you run the program. The %1$tB formatting string in the code above tells the program to use the first argument and print out the full month name for the date object. The %1$te formatting string means to display the day of the month and the %1$tY formatting string is for the four-digit year. Other options for printing dates and times are shown in the Javadoc for the Formatter object. &lt;br /&gt;&lt;br /&gt;String support&lt;br /&gt;The String class has two new static format() methods that work similarly to their printf() equivalents. Send a format string and arguments (with a possible Locale) and use what is specified in the format string to convert the arguments. In the case of the String version of the method, the results are sent back as a String object, instead of going through the stream. These methods aren't overly spectacular, but they allow you to avoid using the Formatter object directly and creating an intermediate StringBuilder. &lt;br /&gt;&lt;br /&gt;Formatting arbitrary objects&lt;br /&gt;Everything you've seen so far describes how to use the new formatting capabilities to format existing objects and primitive types. If you want to provide support for using your own objects with Formatter, that's where the Formattable interface comes into play. By implementing the single formatTo() method shown in Listing 6 in your own class, you can use your own classes with format strings: &lt;br /&gt;&lt;br /&gt;Listing 6. Formattable interface&lt;br /&gt;&lt;br /&gt;void formatTo(Formatter formatter,&lt;br /&gt;              int flags,&lt;br /&gt;              Integer width,&lt;br /&gt;              Integer precision)&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;Listing 7 demonstrates the use of the Formattable interface by providing a simple class with a name property. That name is displayed in the output, with support for controlling the width of the output and the justification. &lt;br /&gt;&lt;br /&gt;Listing 7. Example formattable usage&lt;br /&gt;&lt;br /&gt;import java.util.Locale;&lt;br /&gt;import java.util.Formatter;&lt;br /&gt;import java.util.Formattable;&lt;br /&gt;&lt;br /&gt;public class MyObject implements Formattable {&lt;br /&gt;  String name;&lt;br /&gt;  public MyObject(String name) {&lt;br /&gt;    this.name = name;&lt;br /&gt;  }&lt;br /&gt;  public void formatTo(&lt;br /&gt;         Formatter fmt,&lt;br /&gt;         int f,&lt;br /&gt;         Integer width,&lt;br /&gt;         Integer precision) {&lt;br /&gt;&lt;br /&gt;    StringBuilder sb = new StringBuilder();&lt;br /&gt;    if (precision == null) {&lt;br /&gt;      // no max width&lt;br /&gt;      sb.append(name);&lt;br /&gt;    } else if (name.length() &lt; precision) {&lt;br /&gt;      sb.append(name);&lt;br /&gt;    } else {&lt;br /&gt;      sb.append(name.substring(0, precision - 1)).append('*');&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // apply width and justification&lt;br /&gt;    if ((width != null) &amp;&amp; (sb.length() &lt; width)) {&lt;br /&gt;      for (int i = 0, n=sb.length(); i &lt; width - n; i++) {&lt;br /&gt;        if ((f &amp; Formattable.LEFT_JUSTIFY) == Formattable.LEFT_JUSTIFY) {&lt;br /&gt;          sb.append(' ');&lt;br /&gt;        } else {&lt;br /&gt;          sb.insert(0, ' ');&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    fmt.format(sb.toString());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static void main(String args[]) {&lt;br /&gt;   MyObject my1 = new MyObject("John");&lt;br /&gt;   MyObject my2 = new MyObject("Really Long Name");&lt;br /&gt;   // First / Using toString()&lt;br /&gt;   System.out.println("First Object : " + my1);&lt;br /&gt;   // Second / Using Formatter&lt;br /&gt;   System.out.format("First Object : '%s'\n", my1);&lt;br /&gt;   // Second / Using Formatter&lt;br /&gt;   System.out.format("Second Object: '%s'\n", my2);&lt;br /&gt;   // Second / Using Formatter with width&lt;br /&gt;   System.out.format("Second Object: '%10.5s'\n", my2);&lt;br /&gt;   // Second / Using Formatter with width and left justification&lt;br /&gt;   System.out.format("Second Object: '%-10.5s'\n", my2);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;Running this program produces the output in Listing 8. The first two lines demonstrate the difference between using toString and Formatter. The last three show options for width and justification control. &lt;br /&gt;&lt;br /&gt;Listing 9. Example formattable output&lt;br /&gt;&lt;br /&gt;  First Object : MyObject@10b62c9&lt;br /&gt;  First Object : 'John'&lt;br /&gt;  Second Object: 'Really Long Name'&lt;br /&gt;  Second Object: '     Real*'&lt;br /&gt;  Second Object: 'Real*     '&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;Conclusion&lt;br /&gt;Getting a grasp of all the formatting options available with Formatter will take a little time, unless you are familiar with them from the C world. Some minor differences exist, but for the most part the behaviors are very similar. One key difference with the Java platform is that when the formatting string is invalid, an exception will be thrown. &lt;br /&gt;&lt;br /&gt;Be sure to take a long look at the formatting strings available, as shown in the Formatter class Javadoc. When creating your own custom classes, not only should you provide a toString() implementation, but implementing the Formattable interface will typically be beneficial.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109721573426617237?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109721573426617237/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109721573426617237&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109721573426617237'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109721573426617237'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/taming-tiger-formatted-output-let.html' title='Taming Tiger: Formatted output - Let there be printf'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109697133750022990</id><published>2004-10-05T15:44:00.000+05:30</published><updated>2004-10-05T15:45:37.500+05:30</updated><title type='text'>The GregorianCalendar class </title><content type='html'>One way to create an object representing an arbitrary date is to use the following constructor of the GregorianCalendar class, found in the java.util package: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;GregorianCalendar(int year, int month, int date) &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Note that for the month, January is 0, February is 1, and so on, until December, which is 11. Since those are not the numbers most of us associate with the months of the year, programs will probably be more readable if they use the constants of the parent Calendar class: JANUARY, FEBRUARY, and so on. So, to create an object representing the date that Wilbur and Orville Wright first flew their motored aircraft (December 17, 1903), you can use: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;For clarity's sake, you should use the preceding form. However, you should also learn how to read the shorter form, below. The following example represents the same December 17, 1903, date (remember, in the shorter form 11 represents December): &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;GregorianCalendar firstFlight = new GregorianCalendar(1903, 11, 17);   &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In the previous section, you learned how to turn Date objects into Strings. You will do the same again; but first, you need to convert a GregorianCalendar object to a Date. To do so, you will use the getTime() method, which GregorianCalendar inherits from its parent Calendar class. The getTime() method returns a Date corresponding to a GregorianCalendar object. You can put the whole process of creating a GregorianCalendar object, converting it to a Date, and getting and outputting the corresponding String in the following program: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class Flight {&lt;br /&gt;&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);    &lt;br /&gt;      Date d = firstFlight.getTime();&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      String s = df.format(d);&lt;br /&gt;      System.out.println("First flight was " + s);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Sometimes it is useful to create an instance of the GregorianCalendar class representing the day the instance was created. To do so, simply use the GregorianCalendar constructor taking no arguments, such as: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;GregorianCalendar thisday = new GregorianCalendar();&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;A sample program to output today's date, starting with a GregorianCalendar object is: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;class Today {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      GregorianCalendar thisday = new GregorianCalendar();       Date d = thisday.getTime();&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      String s = df.format(d);&lt;br /&gt;      System.out.println("Today is " + s);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Note the similarities between the Date() constructor and the GregorianCalendar() constructor: both create an object, which in simple terms, represents today. &lt;br /&gt;&lt;br /&gt;Date manipulation &lt;br /&gt;The GregorianCalendar class offers methods for manipulating dates. One useful method is add(). With the add() method, you can add such time units as years, months, and days to a date. To use the add() method, you must supply the field being increased, and the integer amount by which it will increase. Some useful constants for the fields are DATE, MONTH, YEAR, and WEEK_OF_YEAR. The add() method is used in the program below to calculate a date 80 days in the future. Phileas Fogg, the central character in Jules Verne's Around the World in 80 Days, could have used such a program to calculate a date 80 days from his departure on October 2, 1872: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class World {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      GregorianCalendar worldTour = new GregorianCalendar(1872, Calendar.OCTOBER, 2);&lt;br /&gt;      worldTour.add(GregorianCalendar.DATE, 80);&lt;br /&gt;      Date d = worldTour.getTime();&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      String s = df.format(d);&lt;br /&gt;      System.out.println("80 day trip will end " + s);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;While the example is a bit fanciful, adding days to a date is a common operation: video rentals can be due in 3 days, a library may lend books for 21 days, stores frequently require purchased items to be exchanged within 30 days. The following program shows a calculation using years: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class Mortgage {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      GregorianCalendar mortgage = new GregorianCalendar(1997, Calendar.MAY, 18);&lt;br /&gt;      mortgage.add(Calendar.YEAR, 15);&lt;br /&gt;      Date d = mortgage.getTime();&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      String s = df.format(d);&lt;br /&gt;      System.out.println("15 year mortgage amortized on " + s);    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;One important side effect of the add() method is that it changes the original date. Sometimes it is important to have both the original date and the modified date. Unfortunately, you cannot simply create a new GregorianCalendar object set equal to the original. The reason is that the two variables have a reference to one date. If the date is changed, both variables now refer to the changed date. Instead, a new object should be created. The following example will demonstrate this: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class ThreeDates {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      GregorianCalendar gc1 = new GregorianCalendar(2000, Calendar.JANUARY, 1);&lt;br /&gt;      GregorianCalendar gc2 = gc1;&lt;br /&gt;      GregorianCalendar gc3 = new GregorianCalendar(2000, Calendar.JANUARY, 1);&lt;br /&gt;      //Three dates all equal to January 1, 2000&lt;br /&gt;&lt;br /&gt;      gc1.add(Calendar.YEAR, 1);&lt;br /&gt;      //gc1 and gc2 are changed&lt;br /&gt;&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;&lt;br /&gt;      Date d1 = gc1.getTime();&lt;br /&gt;      Date d2 = gc2.getTime();&lt;br /&gt;      Date d3 = gc3.getTime();&lt;br /&gt;&lt;br /&gt;      String s1 = df.format(d1);&lt;br /&gt;      String s2 = df.format(d2);&lt;br /&gt;      String s3 = df.format(d3);&lt;br /&gt;&lt;br /&gt;      System.out.println("gc1 is " + s1);&lt;br /&gt;      System.out.println("gc2 is " + s2);&lt;br /&gt;      System.out.println("gc3 is " + s3);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;After the program is run, gc1 and gc2 are changed to the year 2001 (because both objects are pointing to the same underlying date representation, which has been changed). The object gc3 is pointing to a separate underlying date representation, which has not been changed. &lt;br /&gt;&lt;br /&gt;Calculating review dates &lt;br /&gt;At this point, you have a program based on a real-world example. This particular program will calculate the dates for reviewing material. For example, while reading this article, you might come across some points you want to remember. Unless you have photographic memory, you will likely find that periodically reviewing the new material will aid in remembering it. One reviewing system, discussed in Kurt Hanks and Gerreld L. Pulsipher's Five Secrets to Personal Productivity, suggests briefly covering the material immediately after it is first seen, then after one day, one week, one month, three months, and one year. For this article, you would give it a quick review immediately, another tomorrow, then one week, one month, three months, and one year from now. Our program will calculate the dates. &lt;br /&gt;&lt;br /&gt;To be most useful, the program would be incorporated in PIM (Personal Information Manager) software, which would run the program and schedule the reviews. The getDates() method in the following ReviewDates program would be useful for integrating with electronic software as it returns an array of dates (the review dates). Additionally, you can return individual dates using the methods getFirstDay(), getOneDay(), getOneWeek(), getOneMonth(), and getOneYear(). While it is beyond the scope of this article to integrate the ReviewDates class with a PIM, the ReviewDates class does show how to calculate dates based on elapsed time. Now you can easily modify it for other operations that require elapsed time, such as library loans, tape rentals, and mortgage calculations. First, the ReviewDates class is shown below: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class ReviewDates {&lt;br /&gt;   private GregorianCalendar firstDay, oneDay, oneWeek, oneMonth, oneQuarter, oneYear;&lt;br /&gt;   final int dateArraySize = 6;&lt;br /&gt;&lt;br /&gt;   ReviewDates(GregorianCalendar gcDate) {&lt;br /&gt;      int year = gcDate.get(GregorianCalendar.YEAR);&lt;br /&gt;      int month = gcDate.get(GregorianCalendar.MONTH);&lt;br /&gt;      int date = gcDate.get(GregorianCalendar.DATE);&lt;br /&gt;&lt;br /&gt;      firstDay = new GregorianCalendar(year, month, date);&lt;br /&gt;      oneDay = new GregorianCalendar(year, month, date);&lt;br /&gt;      oneWeek = new GregorianCalendar(year, month, date);&lt;br /&gt;      oneMonth = new GregorianCalendar(year, month, date);&lt;br /&gt;      oneQuarter = new GregorianCalendar(year, month, date);&lt;br /&gt;      oneYear = new GregorianCalendar(year, month, date);&lt;br /&gt;&lt;br /&gt;      oneDay.add(GregorianCalendar.DATE, 1);&lt;br /&gt;      oneWeek.add(GregorianCalendar.DATE, 7);&lt;br /&gt;      oneMonth.add(GregorianCalendar.MONTH, 1);&lt;br /&gt;      oneQuarter.add(GregorianCalendar.MONTH, 3);&lt;br /&gt;      oneYear.add(GregorianCalendar.YEAR, 1);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   ReviewDates() {&lt;br /&gt;      this(new GregorianCalendar());&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void listDates() {&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance(DateFormat.LONG); &lt;br /&gt;      Date startDate = firstDay.getTime();&lt;br /&gt;      Date date1 = oneDay.getTime();&lt;br /&gt;      Date date2 = oneWeek.getTime();&lt;br /&gt;      Date date3 = oneMonth.getTime();&lt;br /&gt;      Date date4 = oneQuarter.getTime();&lt;br /&gt;      Date date5 = oneYear.getTime();&lt;br /&gt;&lt;br /&gt;      String ss =  df.format(startDate);&lt;br /&gt;      String ss1 = df.format(date1);&lt;br /&gt;      String ss2 = df.format(date2);&lt;br /&gt;      String ss3 = df.format(date3);&lt;br /&gt;      String ss4 = df.format(date4);&lt;br /&gt;      String ss5 = df.format(date5);&lt;br /&gt;&lt;br /&gt;      System.out.println("Start date is " + ss);&lt;br /&gt;      System.out.println("Following review dates are:");&lt;br /&gt;      System.out.println(ss1);&lt;br /&gt;      System.out.println(ss2);&lt;br /&gt;      System.out.println(ss3);&lt;br /&gt;      System.out.println(ss4);&lt;br /&gt;      System.out.println(ss5);&lt;br /&gt;      System.out.println();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar[] getDates() {&lt;br /&gt;      GregorianCalendar[] memoryDates = new GregorianCalendar[dateArraySize];&lt;br /&gt;      memoryDates[0] = firstDay;&lt;br /&gt;      memoryDates[1] = oneDay;&lt;br /&gt;      memoryDates[2] = oneWeek;&lt;br /&gt;      memoryDates[3] = oneMonth;&lt;br /&gt;      memoryDates[4] = oneQuarter;&lt;br /&gt;      memoryDates[5] = oneYear;&lt;br /&gt;      return memoryDates;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getFirstDay() {&lt;br /&gt;      return this.firstDay;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getOneDay() {&lt;br /&gt;      return this.oneDay;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getOneWeek() {&lt;br /&gt;      return this.oneWeek;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getOneMonth() {&lt;br /&gt;      return this.oneMonth;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getOneQuarter() {&lt;br /&gt;      return this.oneQuarter;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public GregorianCalendar getOneYear() {&lt;br /&gt;      return this.oneYear;&lt;br /&gt;   }&lt;br /&gt;}  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;An example of a program that uses the ReviewDates class to make a simple listing of review dates is shown below: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;&lt;br /&gt;public class ShowDates {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      ReviewDates rd = new ReviewDates();&lt;br /&gt;      rd.listDates();&lt;br /&gt;&lt;br /&gt;      GregorianCalendar gc = new GregorianCalendar(2001, Calendar.JANUARY, 15);&lt;br /&gt;      ReviewDates jan15 = new ReviewDates(gc);&lt;br /&gt;      jan15.listDates();&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Conclusion &lt;br /&gt;This article has introduced three important classes for working with dates: Date, DateFormat, and GregorianCalendar. These classes let you create dates, change them into Strings, and make elementary calculations with dates. In terms of working with dates in Java, this article has only scratched the surface. However, the classes and methods that I have introduced here not only serve as springboard for more advanced learning, but in themselves can also handle many common date-related tasks.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109697133750022990?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109697133750022990/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109697133750022990&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109697133750022990'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109697133750022990'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/gregoriancalendar-class.html' title='The GregorianCalendar class '/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109697123893611417</id><published>2004-10-05T15:39:00.000+05:30</published><updated>2004-10-05T15:43:58.936+05:30</updated><title type='text'>Calculating Java dates </title><content type='html'>To keep track of time, Java counts the number of milliseconds from the start of January 1, 1970. This means, for example, that January 2, 1970, began 86,400,000 milliseconds later. Similarly, December 31, 1969, began 86,400,000 milliseconds before January 1, 1970. The Java Date class keeps track of those milliseconds as a long value. Because long is a signed number, dates can be expressed before and after the start of January 1, 1970. The largest positive and negative values expressible by the long primitive can generate dates forward and backward about 290,000,000 years, which suits most people's schedules. &lt;br /&gt;&lt;br /&gt;The Date class &lt;br /&gt;The Date class, found in the java.util package, encapsulates a long value representing a specific moment in time. One useful constructor is Date(), which creates a Date object representing the time the object was created. The getTime() method returns the long value of a Date object. In the program below, I use the Date() constructor to create a date based on when the program was run, and the getTime() method to find out the number of milliseconds that the date represents: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;public class Now {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      Date now = new Date();&lt;br /&gt;      long nowLong = now.getTime();&lt;br /&gt;      System.out.println("Value is " + nowLong);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When I ran that program, it gave me a value of 972,568,255,150. A quick check with my calculator confirms this number is at least in the correct ballpark: it's a bit less than 31 years, which corresponds to the right number of years between January 1, 1970, and the day I wrote this article. While computers may thrive on numbers like the foregoing value, most people are reluctant to say such things as "I'll see you on 996,321,998,346." Fortunately, Java provides a way to convert Date objects to Strings, which represent dates in more traditional ways. The DateFormat class, discussed in the next section, can create Strings with alacrity. &lt;br /&gt;&lt;br /&gt;The DateFormat class &lt;br /&gt;One purpose of the DateFormat class is to create Strings in ways that humans can easily deal with them. However, because of language differences, not all people want to see a date in exactly the same way. Someone in France may prefer to see "25 decembre 2000," while someone in the United States may be more accustomed to seeing "December 25, 2000." So when an instance of a DateFormat class is created, the object contains information concerning the particular format in which the date is to be displayed. To use the default format of the user's computer, you can apply the getDateInstance method in the following way to create the appropriate DateFormat object: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;DateFormat df = DateFormat.getDateInstance();   &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The DateFormat class is found in the java.text package. &lt;br /&gt;&lt;br /&gt;Converting to a String &lt;br /&gt;You can convert a Date object to a string with the format method. This is shown in the following demonstration program: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class NowString {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      Date now = new Date();&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      String s = df.format(now);&lt;br /&gt;      System.out.println("Today is " + s);&lt;br /&gt;   }&lt;br /&gt;}  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The getDateInstance method shown in the code above, with no arguments, creates an object in the default format or style. Java also provides some alternative styles for dates, which you can obtain through the overloaded getDateInstance(int style). For convenience' sake, DateFormat provides some ready-made constants that you can use as arguments in the getDateInstance method. Some examples are SHORT, MEDIUM, LONG, and FULL, which are demonstrated in the program below: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class StyleDemo {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      Date now = new Date();&lt;br /&gt;&lt;br /&gt;      DateFormat df =  DateFormat.getDateInstance();&lt;br /&gt;      DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);&lt;br /&gt;      DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);&lt;br /&gt;      DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);&lt;br /&gt;      DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL); &lt;br /&gt;      String s =  df.format(now);&lt;br /&gt;      String s1 = df1.format(now);&lt;br /&gt;      String s2 = df2.format(now);&lt;br /&gt;      String s3 = df3.format(now);&lt;br /&gt;      String s4 = df4.format(now);&lt;br /&gt;&lt;br /&gt;      System.out.println("(Default) Today is " + s);&lt;br /&gt;      System.out.println("(SHORT)   Today is " + s1);&lt;br /&gt;      System.out.println("(MEDIUM)  Today is " + s2);&lt;br /&gt;      System.out.println("(LONG)    Today is " + s3);&lt;br /&gt;      System.out.println("(FULL)    Today is " + s4);&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;That program output the following: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;(Default) Today is Nov 8, 2000&lt;br /&gt;(SHORT)   Today is 11/8/00&lt;br /&gt;(MEDIUM)  Today is Nov 8, 2000&lt;br /&gt;(LONG)    Today is November 8, 2000&lt;br /&gt;(FULL)    Today is Wednesday, November 8, 2000&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The same program, after being run on my computer with the default regional settings changed to Swedish, displayed this output: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;(Default) Today is 2000-nov-08&lt;br /&gt;(SHORT)   Today is 2000-11-08&lt;br /&gt;(MEDIUM)  Today is 2000-nov-08&lt;br /&gt;(LONG)    Today is den 8 november 2000&lt;br /&gt;(FULL)    Today is den 8 november 2000      &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;From that, you can see that in Swedish the months of the year are not capitalized (although November is still november). Also, note that the LONG and FULL versions are identical in Swedish, while they differ in American English. Additionally, it is interesting that the Swedish word for Wednesday, onsdag, is not included in the FULL version, where the English FULL version includes the name of the day. &lt;br /&gt;&lt;br /&gt;Note that you can use the getDateInstance method to change the language for a DateFormat instance; however, in the case above, it was done on a Windows 98 machine by changing the regional settings from the control panel. The lesson here is that the default regional setting varies from place to place, which has both advantages and disadvantages of which the Java programmer should be aware. One advantage is that the Java programmer can write a single line of code to display a date, yet have the date appear in tens or even hundreds of different forms when the program is run on computers throughout the world. But that can be a disadvantage if the programmer wants just one format -- which is preferable, for example, in a program that outputs text and dates mixed together. If the text is in English, it would be inconsistent to have dates in other formats, such as German or Spanish. If the programmer relies on the default regional format, the date format will vary according to the executing computer's regional settings. &lt;br /&gt;&lt;br /&gt;Parsing a String &lt;br /&gt;You can also use the DateFormat class to create Date objects from a String, via the parse() method. This particular method can throw a ParseException error, so you must use proper error-handling techniques. A sample program that turns a String into a Date is shown below: &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import java.util.*;&lt;br /&gt;import java.text.*;&lt;br /&gt;&lt;br /&gt;public class ParseExample {&lt;br /&gt;   public static void main(String[] args) {&lt;br /&gt;      String ds = "November 1, 2000";&lt;br /&gt;      DateFormat df = DateFormat.getDateInstance();&lt;br /&gt;      try {&lt;br /&gt;         Date d = df.parse(ds);&lt;br /&gt;      }&lt;br /&gt;      catch(ParseException e) {&lt;br /&gt;         System.out.println("Unable to parse " + ds);&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The parse() method is a useful tool for creating arbitrary dates. I will examine another way of creating arbitrary dates. Also, you will see how to do elementary calculations with dates, such as calculating the date 90 days after another date. You can accomplish both tasks with the GregorianCalendar class.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109697123893611417?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109697123893611417/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109697123893611417&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109697123893611417'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109697123893611417'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/calculating-java-dates.html' title='Calculating Java dates '/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109695105018324765</id><published>2004-10-05T10:05:00.000+05:30</published><updated>2004-10-05T10:07:30.183+05:30</updated><title type='text'>Generating excel file as well as redirecting to a different page</title><content type='html'>You might be able to accomplish what you want with clever use of javascript on the client.&lt;br /&gt;&lt;br /&gt;For example, put the following in a SCRIPT tag:&lt;br /&gt;function launchExcel() {&lt;br /&gt;    newWindow = window.open('excelservlet','_blank');&lt;br /&gt;    window.location.href='downloadsuccess.jsp';&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;And the link to the Excel file in your JSP should have this attribute: onclick="javascript:launchExcel();"&lt;br /&gt;&lt;br /&gt;This will cause the Excel sheet to be loaded by a separate window, and the current window will navigate to the "excel file successfully generated" page. &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109695105018324765?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109695105018324765/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109695105018324765&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109695105018324765'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109695105018324765'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/generating-excel-file-as-well-as.html' title='Generating excel file as well as redirecting to a different page'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8580915.post-109687080089243747</id><published>2004-10-04T11:47:00.000+05:30</published><updated>2004-10-04T15:54:22.186+05:30</updated><title type='text'>Java Final Release</title><content type='html'>Hello Friends ,&lt;br /&gt;&lt;br /&gt;Sun Has Finally released Javas lattest Version : &lt;strong&gt;J2sdk&lt;/strong&gt; &lt;strong&gt;5&lt;/strong&gt; on 30th of September&lt;br /&gt;Read More About It On The (&lt;a href="http://www.theserverside.com"&gt;www.theserverside.com&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;Enjoy .......&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8580915-109687080089243747?l=javasuccess.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javasuccess.blogspot.com/feeds/109687080089243747/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8580915&amp;postID=109687080089243747&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109687080089243747'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8580915/posts/default/109687080089243747'/><link rel='alternate' type='text/html' href='http://javasuccess.blogspot.com/2004/10/java-final-release.html' title='Java Final Release'/><author><name>Amit Sharma</name><uri>http://www.blogger.com/profile/10150777710569395521</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
