Wednesday, December 05, 2007

Waoo - Netbeans 6 is Available

The much awaited IDE NetBeans 6 is out today. In morning when i saw the email from net beans stating:
[nbannounce] NetBeans IDE 6.0 Available.
I couldn't stop myself from digging its features. It supports almost all current technologies and standard of Java/J2EE/Web Services/SOA.

Even, I ordered for a Free starter kit DVD. So why Don't you order or download the NetBeans 6 Today. NetBeans is easy to use IDE. Here is link to order a Starter Kit:
Get My Own NetBeans 6 Starter Kit.
or Click the Image to get It:

NetBeans 6 DVD includes:
NetBeans IDE 6.0 with all packs
Java(TM) Platform Standard Edition Development Kit (JDK) 6.0 Update 3,
Java Tutorials,
NetBeans tutorials and screencasts.

Following Operating Systems are Supported:

Solaris x86,
Solaris SPARC
Mac OS X.

Currently, The NetBeans starter kit is available in English language, but very soon it will be available in other languages also.

So what are you waiting for. Just register and Get it.

Sunday, October 14, 2007

Google Desktop Search - Awesome Tool

Hi Friends,

I found something very interesting something about google desktop search. I think, it is really useful to share with you people.

Google Desktop Search acts as your own personal Google Server and indexes the contents your system by file name, or in the case of select file formats, by the contents of the file. It runs on Windows XP and Windows 2000 (with Service Pack 3).

The free download indexes the full text of email created in Outlook or Outlook Express, Word documents, Excel spreadsheets, PowerPoint presentations, AOL Instant Messages, and caches the pages you view in Internet Explorer so you can revisit the page later "even if its live content has changed or you're offline."

The install is really simple and after you install it starts indexing. If you are working on your system then it will take a while to index. As soon as it realizes the machine is idle it starts churning away. After it indexes the data you are presented with a browser based interface much like the google we all know. Yes is it lightening fast, typing in JRun on my machine turned up 24,107 entries for files and 27,823 for web history, all that in .5 seconds. It looks through basically anything on your machine and indexes it. For free you can't beat this. it is on my short list of the best windows utilities I have ever used.

So what are you thinking, just download the Google Pack, It contains All the necessary softwares, which makes your PC useful....
Download it from Here

Wednesday, October 10, 2007

Manipulating String intelligently

Performance and Optimizations are the key features desired in Java Programming. So here are some examples, how to make improvement in your String manipulation..

String is the most encountered Objects in Java Programming. Till Tiger, we have 3 Classes to manipulate Strings. These are String, StringBuilder, StringBuffer.

String is immutable whereas StringBuffer and StringBuilder can change their values.

StringBuilder was introduced in J2SE5 or Tiger.The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Here are some examples given by Mr. Heinz Kabutz about how to perform String Manipulation intelligently.

We start with a basic concatenation based on +=:

public static String concat1(String s1, String s2, String s3,
String s4, String s5, String s6) {
String result = "";
result += s1;
result += s2;
result += s3;
result += s4;
result += s5;
result += s6;
return result;

String is immutable, so the compiled code will create many intermediate String objects, which can strain the garbage collector. A common remedy is to introduce StringBuffer, causing it to look like this:

public static String concat2(String s1, String s2, String s3,
String s4, String s5, String s6) {
StringBuffer result = new StringBuffer();
return result.toString();

But the code is becoming less legible, which is undesirable.

Using JDK 6.0_02 and the server HotSpot compiler, I can execute concat1() a million times in 2013 milliseconds, but concat2() in 734 milliseconds. At this point, I might congratulate myself for making the code three times faster. However, the user won't notice it if 0.1 percent of the program becomes three times faster.

Here's a third approach that I used to make my code run faster, back in the days of JDK 1.3. Instead of creating an empty StringBuffer, I sized it to the number of required characters, like so:

public static String concat3(String s1, String s2, String s3,
String s4, String s5, String s6) {
return new StringBuffer(
s1.length() + s2.length() + s3.length() + s4.length() +
s5.length() + s6.length()).append(s1).append(s2).

I managed to call that a million times in 604 milliseconds. Even faster than concat2(). But is this the best way to add the strings? And what is the simplest way?

The approach in concat4() illustrates another way:

public static String concat4(String s1, String s2, String s3,
String s4, String s5, String s6) {
return s1 + s2 + s3 + s4 + s5 + s6;

You can hardly make it simpler than that. Interestingly, in Java SE 6, I can call the code a million times in 578 milliseconds, which is even better than the far more complicated concat3(). The method is cleaner, easier to understand, and quicker than our previous best effort.

Sun introduced the StringBuilder class in J2SE 5.0, which is almost the same as StringBuffer, except it's not thread-safe. Thread safety is usually not necessary with StringBuffer, since it is seldom shared between threads. When Strings are added using the + operator, the compiler in J2SE 5.0 and Java SE 6 will automatically use StringBuilder. If StringBuffer is hard-coded, this optimization will not occur.

When a time-critical method causes a significant bottleneck in your application, it's possible to speed up string concatenation by doing this:

public static String concat5(String s1, String s2, String s3,
String s4, String s5, String s6) {
return new StringBuilder(
s1.length() + s2.length() + s3.length() + s4.length() +
s5.length() + s6.length()).append(s1).append(s2).

However, doing this prevents future versions of the Java platform from automatically speeding up the system, and again, it makes the code more difficult to read.

Source: By Mr. Heinz Kabutz(Java Champions) (creator of the free Java Specialists' Newsletter)

Sunday, August 19, 2007

Calendar class - Better Way to Manipulate Dates.

Java’s Calendar class offers a set of methods for converting and manipulating temporal information. In addition to retrieving the current date and time, the Calendar class also provides an API for date arithmetic. Calendar’s built-in date/time arithmetic API is extremely useful.

This tutorial examines the Calendar class API and presents examples of how you can use Calendar objects to add and subtract time spans to and from dates and times, as well as how to evaluate whether one date precedes or follows another.

Adding time spans

Let’s say you want to add a time span to a starting date and print the result. Consider the following example, which initializes a Calendar to 16 July 2007 and then adds two months and three days to it to obtain a new value:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;     
public class CalenderDemo{
 public static void main(String[] args) {
  CalenderDemo tdt = new CalenderDemo();
 private void calculateDate(){
  //Creating a calendar instance with initial date
16 July 2007
  Calendar calendar = new GregorianCalendar
  System.out.println("Initial date is: ");
  // Adding 2 Months and 3 day here
  // printing modified date value
  System.out.println("New date is: ");
 /** Method to print Formatted Date
SimpleDateFormat */
 private void printFormattedDate(Calendar calendar){
  // define output format and print
  SimpleDateFormat sdf = new SimpleDateFormat
("d MMM yyyy hh:mm aaa");
  String date = sdf.format(calendar.getTime());

The main workhorse of this class is the doMath() method, which begins by initializing a new GregorianCalendar object to 16 July 2007. Next, the object’s add() method is invoked; this method accepts two arguments: the name of the field to add the value to and the amount of time to be added. In this example, the add() method is called twice — first to add two months to the starting date and then to add a further one day to the result. Once the addition is performed, the printCalendar() utility method is used to print the final result.

The use of the SimpleDateFormat object to turn the output of getTime() into a human-readable string. This class is a part of java.text. package.

When you run the class, this is the output you’ll see:

Initial date is:
 16 July 2007 12:00 AM
New date is:
 19 September 2007 12:00 AM

This kind of addition also works with time values. To illustrate, consider the next example, which adds 14 hours and 55 minutes to a starting time value:

* Creating an Instance of Calendar with Year,
* Month, data, Hours and Minutes **/
Calendar calendar =new GregorianCalendar
(2007,Calendar.JANUARY,1, 1,0);
System.out.println(“Initial Date is :”);
//Defined in Above example
 // Add 14h 55min
//Print after Adding the hours and minutes        
System.out.println(“Modified Date is :”);
printFormattedDate(calendar);  //Defined in Above example.
This is almost identical to the previous class except
that the calls to add() involve the calendar’s hour
and minute fields. Here’s the output:
Initial Date is:

1 Jan 2007 01:00 AM

Modified Date is
1 Jan 2007 03:55 PM

Subtracting time spans

Subtraction is fairly easy as well — you simply use negative values as the second argument to add(). Here’s an example:

// Creating a Date Instance with Year, Month, Day, Hours and Minutes
Calendar calendar = new GregorianCalendar
(2007,Calendar.JANUARY,2, 3,30);
System.out.println("Starting date is: ");
//Defined in First Example.
// Subtracting 1 Year 1 Day 4 Hours and 5 Minutes
System.out.println("Subtracting 1 Year 1
Day 4 Hours and 5 Minutes");
// print result
System.out.println("Ending date is ");

Here’s the output:

Starting date is:
2 Jan 2007 03:30 AM
Subtracting 1y 1d 4h 5min...
Ending date is
31 Dec 2005 11:25 PM

In this example, the Calendar object automatically takes care of adjusting the year and the day when the subtraction results in the date “overflowing” from 1 Jan 2006 to 31 Dec 2005.

Adding vs. rolling

As the previous example illustrates, the add() method automatically takes care of rolling over days, months, and years when a particular calendar field “overflows” as a result of addition or subtraction. However, this behavior is often not what you want. In those situations, the Calendar object also has a roll() method, which avoids incrementing or decrementing larger calendar fields when such overflow occurs. To see how this works, look at the following example:

Calendar calendar = new GregorianCalendar
(2006, Calendar.DECEMBER,1);
System.out.println("Starting date for add()  is: ");
System.out.println("After add()ing 1 month, ending date is: ");
calendar.add(Calendar.MONTH, 1);
// initialize calendar
Calendar calendar2 = new GregorianCalendar

(2006, Calendar.DECEMBER,1);
System.out.println("Starting date for roll() is: ");
System.out.println("After roll()ing 1 month,  ending date is: ");
Calendar2.roll(Calendar.MONTH, 1);

Here’s the output:

Starting date for add() is:
 1 Dec 2006 12:00 AM
 After add()ing 1 month, ending date is:
 1 Jan 2007 12:00 AM     
 Starting date for roll() is:
 1 Dec 2006 12:00 AM
 After roll()ing 1 month, ending date is:
 1 Jan 2006 12:00 AM

In the first case, when one month is added to the starting date of 1 Dec 2006, the add() method realizes that a year change will occur as a result of the addition, and the year is rolled over to 2007. When using roll(), this behavior is disabled, and only the month field is incremented by 1, with the year change ignored. In many situations, roll() is very useful.

Checking date precedence

The Calendar object also includes the compareTo() method, which lets you compare two dates to find out which one comes earlier. The compareTo() method accepts another Calendar object as an input argument and returns a value less than zero if the following conditions are true:

  • The date and time of the input Calendar object is later than that of the calling Calendar object.
  • A value greater than zero if the reverse is true.
  • A value of 0 if the two Calendar objects represent the same date.

Here’s an example that compares 1 Jan 2007 12:00 AM and 1 Jan 2007 12:01 AM with compareTo():

// initialize two calendars
Calendar calendar1 = new GregorianCalendar
Calendar calendar2 = new GregorianCalendar
// define date format
String date1 = null;
String date2 = null;
SimpleDateFormat sdf = new SimpleDateFormat
("d MMM yyyy hh:mm aaa");
// compare dates
if((calendar1.compareTo(calendar2)) <>
    date1 = sdf.format(calendar1.getTime());
    date2 = sdf.format(calendar2.getTime());
    date1 = sdf.format(calendar2.getTime());
    date2 = sdf.format(calendar1.getTime());
System.out.println(date1 + " occurs before " + date2);
System.out.println(date2 + " occurs after  " + date1);

Here’s the output:

1 Jan 2007 12:00 AM occurs before 1 Jan 2007 12:01 AM
1 Jan 2007 12:01 AM occurs after  1 Jan 2007 12:00 AM

Since Most of the Date/Time classes are deprecated,
Calendar class is very handy to work with.
Alongwith this java.text.DateFormat and
java.text.SimpleDateFormat are very useful to
convert the date to different Locales and
different format.

Thursday, August 09, 2007

Reflection APIs - A way to inspect classes at runtime

Java Reflection is a technology that looks inside a Java object at runtime and sees basically everything about the object that you would know at compile time.

Java Reflection is a technology that looks inside a Java object at runtime and sees what variables it contains, what methods it supports, what interfaces it implements, what classes it extends—basically everything about the object that you would know at compile time.

The Reflection API is located in the java.lang.reflect package and is included in any J2SE installation. Primarily it is intended for very generic programs such as database browsers or visual code editors, but it can be used in any other applications. Reflection is for

Basic techniques

There are two basic techniques involved in Reflection: discovery and use by name. Here are descriptions of both:

  • Discovery involves taking an object or class and discovering the members, superclasses, implemented interfaces, and then possibly using the discovered elements.
  • Use by name involves starting with the symbolic name of an element and using the named element.

Discovery typically starts with an object and then calls the Object.getClass() method to get the object's Class. The Class object has a number of methods for discovering the contents of the class. Here are some of those methods:

  • getMethods(): returns an array of Method objects representing all of the public methods of the class or interface.
  • getConstructors(): returns an array of Constructor objects representing all of the public constructors of the class.
  • getFields(): returns an array of Field objects representing all of the public fields of the class or interface.
  • getClasses(): returns an array of Class objects representing all of the public classes and interfaces that are members (e.g., inner classes) of the class or interface.
  • getSuperclass(): returns the Class object representing the superclass of the class or interface (null is returned for interfaces).
  • getInterfaces(): returns an array of Class objects representing all of the interfaces that are implemented by the class or interface.

You can obtain the Class object either through discovery, by using the class literal (e.g., MyClass.class), or by using the name of the class (e.g., Class.forName("mypackage.MyClass")). With a Class object, member objects Method, Constructor, or Field can be obtained using the symbolic name of the member. These are the most important techniques:

  • getMethod("methodName", Class...): returns the Method object representing the public method with the name "methodName" of the class or interface that accepts the parameters specified by the Class... parameters.
  • getConstructor(Class...): returns the Constructor object representing the public constructor of the class that accepts the parameters specified by the Class... parameters.
  • getField("fieldName"): returns the Field object representing the public field with the name "fieldName" of the class or interface.

You can use Method, Constructor, and Field objects to dynamically access the represented member of the class. For example:

  • Field.get(Object): returns an Object containing the value of the field from the instance of the object passed to get(). (If the Field object represents a static field, the Object parameter is ignored and may be null.)
  • Method.invoke(Object, Object...): returns an Object containing the result of invoking the method for the instance of the first Object parameter passed to invoke(). The remaining Object... parameters are passed to the method. (If the Method object represents a static method, the first Object parameter is ignored and may be null.)
  • Constructor.newInstance(Object...): returns the new Object instance from invoking the constructor. The Object... parameters are passed to the constructor. (Note that the parameterless constructor for a class can also be invoked by calling newInstance().)

Creating arrays and proxy classes

The java.lang.reflect package provides an Array class that contains static methods for creating and manipulating array objects. Since J2SE 1.3, the java.lang.reflect package also provides a Proxy class that supports dynamic creation of proxy classes, which implement specified interfaces.

The implementation of a Proxy class is provided by a supplied object that implements the InvocationHandler interface. The InvocationHandler's method invoke (Object, Method, Object[]) is called for each method invoked on the proxy object—the first parameter is the proxy object, the second parameter is the Method object representing the method from the interface implemented by the proxy, and the third parameter is the array of parameters passed to the interface method. The invoke() method returns an Object result that contains the result returned to the code that called the proxy interface method.

Eaxmple of Reflection is :

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Member;
import static java.lang.System.out;
public class ClassSpy {
    public static void main(String... args) {
               try {
                   Class c = Class.forName(args[0]);
                   out.format("Class:%n  %s%n%n", c.getCanonicalName());
                   Package p = c.getPackage();
                   out.format("Package:%n  %s%n%n",
                                      (p != null ? p.getName() : "-- No Package --"));
                   for (int i = 1; i <>
                               switch (ClassMember.valueOf(args[i])) {
                               case CONSTRUCTOR:
                                   printMembers(c.getConstructors(), "Constructor");
                               case FIELD:
                                   printMembers(c.getFields(), "Fields");
                               case METHOD:
                                   printMembers(c.getMethods(), "Methods");
                               case CLASS:
                               case ALL:
                                   printMembers(c.getConstructors(), "Constuctors");
                                   printMembers(c.getFields(), "Fields");
                                   printMembers(c.getMethods(), "Methods");
                                   assert false;
        // production code should handle these exceptions more gracefully
               } catch (ClassNotFoundException x) {
    private static void printMembers(Member[] mbrs, String s) {
               out.format("%s:%n", s);
               for (Member mbr : mbrs) {
                   if (mbr instanceof Field)
                               out.format("  %s%n", ((Field)mbr).toGenericString());
                   else if (mbr instanceof Constructor)
                               out.format("  %s%n", ((Constructor)mbr).toGenericString());
                   else if (mbr instanceof Method)
                               out.format("  %s%n", ((Method)mbr).toGenericString());
               if (mbrs.length == 0)
                   out.format("  -- No %s --%n", s);
    private static void printClasses(Class c) {
               Class[] clss = c.getClasses();
               for (Class cls : clss)
                   out.format("  %s%n", cls.getCanonicalName());
               if (clss.length == 0)
                   out.format("  -- No member interfaces, classes, or enums --%n");

Further References:

Friday, July 27, 2007

Java Singleton Pattern : Potential Problems and Solutions

The Java Singleton pattern belongs to the family of design patterns that governs the instantiation process. This design pattern suggests that at any time there can only be one instance of a Singleton (object) created by the JVM. You implement the pattern by creating a class with a method that creates a new instance of the class if one does not exist. If an instance of the class exists, it simply returns a reference to that object.

How the Singleton pattern works:

Here’s a typical example of Singleton:

public class Singleton {
        private final static Singleton INSTANCE = new Singleton();
      // Private constructor suppresses generation of
    // a (public) default constructor
    private Singleton() {}
    public static Singleton getInstance() {
      return INSTANCE;

The classic Singleton does not use direct instantiation of a static variable with declaration — it instantiates a static instance variable in the constructor without checking to see if it already exists:

public class ClassicSingleton {
    private static ClassicSingleton INSTANCE = null;
    private ClassicSingleton() {
       // Exists only to defeat instantiation.
    public static ClassicSingleton getInstance() {
       if(INSTANCE == null) {
          INSTANCE = new ClassicSingleton();
       return INSTANCE;
Or alternative way is :
public class ClassicSingleton {
    private static ClassicSingleton INSTANCE = null;
                 INSTANCE = new ClassicSingleton();
    private ClassicSingleton() {
       // Exists only to defeat instantiation.
    public static ClassicSingleton getInstance() {      
       return INSTANCE;

The static construct ensure that the object is created when the class is loaded by the JVM. The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by other classes using the new keyword. A static modifier is applied to the instance method that returns the Singleton object; it makes this a class level method that can be accessed without creating an object.

When you need Singleton

Singletons are truly useful when you need only one instance of a class, and it is undesirable to have more than one instance of a class.

When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.

Check out for potential problems

Although the Singleton design pattern is one of the simplest design patterns, it has some limitations.

Construct in multi-threaded applications
You must carefully construct the Singleton pattern in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not exist, both must check for an instance of the Singleton, but only one thread should create the new object. The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated. This is a thread-safe version of a Singleton:

public class Singleton
   // Private constructor suppresses generation
   //  of a (public) default constructor
   private Singleton() {}
   private static class SingletonHolder{
     private final static Singleton INSTANCE = new Singleton();
   public static Singleton getInstance(){
     return SingletonHolder.INSTANCE;

For an alternative solution, you can add the synchronized keyword to the getInstance() method declaration:

   public static synchronized Singleton getInstance()

Think ahead about cloning prevention
You can still create a copy of the Singleton object by cloning it using the Object’s clone() method. To forbid this, you need to override the Object’s clone method, which throws a CloneNotSupportedException exception:

      public Object clone() throws CloneNotSupportedException {
         throw new CloneNotSupportedException();

Consider making the singleton class final
You may want to make the Singleton class final to avoid sub classing of Singletons that may cause other problems.

Remember about garbage collection
Depending on your implementation, your Singleton class and all of its data might be garbage collected. This is why you must ensure that there must be a live reference to the Singleton class when the application is running.

The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming.

Friday, January 05, 2007

Struts Are the Really Very Beautiful..................

Three Days Before Struts started in Training program. I Heard that Struts are very difficult to understand. But After three days, I found how beautifully they are designed by the Craig R. McClanahan.

I also learned Here in current company that learning the concepts is very neccessary rather than just gulping the APIS. I really thank our instructor for this.

Hey I m not going to write about the struts, since web is just full of such kind of material. The spirit is to force urself to learn the basics of anything. Technology may change not the basic concepts.

Time to Take a Break.