Java Tips, Hacks, Updates

These are some of the best practices that have helped me in being more productive and efficient at design and development of J2ee
application. These may also help you in dealing with and avoiding potential coding and design issues in your applications.

Implementing Comparable and understanding compareTo

posted 17 Apr 2012, 00:04 by Sanjeev Kumar   [ updated 17 Apr 2012, 00:06 ]

Implementing Comparable

Implementing Comparable allows:
  1. Calling Collections.sort and Collections.binarySearch.
  2. Calling Arrays.sort and Arrays.binarySearch.
  3. Using objects as keys in a TreeMap.
  4. Using objects as elements in a TreeSet.

Understanding compareTo

The compareTo() method is the sole member of Comparable interface. It provides a means of fully ordering objects. For a concrete comparable implementation class to work well, the compareTo() implementation needs to satisfy the certain conditions.
  1. Anti Commutation :  x.compareTo(y) is the opposite sign of y.compareTo(x)
  2. Exception Symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x)
  3. Transitivity : 
    1. if x.compareTo(y) > 0 and y.compareTo(z) > 0, then x.compareTo(z) > 0  (and same for less than)
    2. if x.compareTo(y)==0, then x.compareTo(z) has the same sign as y.compareTo(z)
  4. consistency with equals : It is highly recommended, but not required : x.compareTo(y) == 0, if and only if x.equals(y) ; consistency with equals is required for ensuring sorted collections (such as TreeSet) are well-behaved.

Things to remember while implementing compareTo()

Compare the various types of fields as follows :
  1. Numeric primitive : use < and >. There is an exception to this rule: float and double primitives should be compared using Float.compare(float, float) and Double.compare(double, double). This avoids problems associated with special border values.
  2. Boolean primitive :  use tests of the form (x && !y)
  3. Object : use compareTo. (Note that possibly-null fields present a problem : while x.equals(null) returns false, x.compareTo(null) will always throw a NullPointerException)
  4. Type-safe enumeration : use compareTo, like any Object
  5. collection or array : Comparable does not seem to be intended for these kinds of fields. For example, List, Map and Set do not implement Comparable. As well, some collections have no definite order of iteration, so doing an element-by-element comparison cannot be meaningful in those cases.

Comparable implementations in JDK

All primitive wrapper classes like Integer, Long, Float, Double, Boolean and many more implement Comparable. 

Hot tips

  1. One can greatly increase the performance of compareTo by comparing first on items which are most likely to differ.
  2. Avoid instanceof in methods that override or implement Object.equals(), Comparable.compareTo()
  3. If the task is to perform a sort of items which are stored in a relational database, then it is usually much preferred to let the database perform the sort using the ORDER BY clause, rather than in code.
  4. An alternative to implementing Comparable is passing Comparator objects as parameters. Be aware that if a Comparator compares only one of several significant fields, then the Comparator is very likely not synchronized with equals.
  5. When a class extends a concrete Comparable class and adds a significant field, a correct implementation of compareTo cannot be constructed. The only alternative is to use composition instead of inheritance. (A similar situation holds true for equals. See Effective Java for more information.)

Exception Handling Guidelines/Best Practices

posted 5 Apr 2012, 03:25 by Sanjeev Kumar   [ updated 17 Apr 2012, 02:34 ]

Let’s review some basic exception design guidelines, summarized from Object Design: Roles, Responsibilities, and Collaborations (Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley, 2003).

Don’t try to handle coding errors.

Unless your software is required to take extraordinary measures in error scenarios, don’t spend a lot of time designing it to detect and recover from programming errors. In the case of an out-of-bounds array index, divide-by zero error, or any other programming error, the best strategy is to fail fast (and leave an audit trail of the problem that can be used to troubleshoot it).

Avoid declaring lots of exception classes.

Create a new exception class only when you expect some handling of the code to take a significantly different action, based on the exception type. In my experience it is rarely the case and exception classes available in java API serve the purpose.

Recast lower-level exceptions to higher-level ones whenever you raise an abstraction level.

Don’t let implementation details leak out of a method invocation as exceptions. Otherwise, your users might think your software is broken. When low-level exceptions percolate up to a high-level handler, there’s little context to assist the handler in making informed decisions or reporting conditions that are traceable to any obvious cause. Recasting an exception whenever you cross an abstraction boundary enables exception handlers higher up in the call chain to make more informed decisions. If you want to include a problem trace when recasting them, you can always create a chained exception. A chained exception provides added context and holds a reference to the original lower level exception. You can repeatedly chain exceptions.

Provide context along with an exception.

What’s most important in exception handling is information that helps create an informed response. Exception classes hold information. You can design them to be packed with information in addition to the bare-bones stack trace information provided by default. You might include values of parameters that raised the exception, specific error text, or detailed information that could be useful to plan a recovery. When an exception occurs, it is important that all pertinent data be passed to the exception's constructor. Such data is often critical for understanding and solving the problem, and can greatly reduce the time needed to find a solution.

The this reference is sometimes useful for this purpose, since toString is implicitly called. In addition, if you are defining exception classes yourself, you may even design your constructors to force the caller to pass the pertinent data.

Uninformative stack traces are very frustrating for the maintainer, and often inspire even the most well-tempered programmers to temporarily violate local community standards for obscenity.

Example

public final class RangeChecker {

  /**
  * Return <code>true</code> only if <code>aNumber</code> is in the range
  * <code>aLow..aHigh</code> (inclusive).
  *
  * @param <code>aLow</code> less than or equal to <code>aHigh</code>.
  */
  static public boolean isInRange( int aNumber, int aLow, int aHigh ){
    if (aLow > aHigh) {
      throw new IllegalArgumentException("Low:" + aLow + " greater than High:" + aHigh);
    }
    return (aLow <= aNumber && aNumber <= aHigh);
  }
}

Handle exceptions as close to the problem as you can.

As a first line of defense, consider the initial requestor. If the caller knows enough to perform a corrective action, you can rectify the condition on the spot. If you propagate an exception far away from the source, it can be difficult to trace the source. Often objects further away from the problem can’t make meaningful decisions.

Use exceptions only to signal emergencies.

Exceptions shouldn’t be raised to indicate normal branching conditions that will alter the flow in the calling code. For example, a find operation may return zero, one, or many objects, so I wouldn’t raise an exception in this case. Instead, I’d design my find() method to return a null object or an empty collection. A dropped database connection, on the other hand, is a real emergency. There’s nothing that can be done to continue as planned.

Don’t repeatedly re-throw the same exception.

Although exceptions don’t cost anything until they’re raised, programs that frequently raise exceptions run more slowly.

Avoid empty catch blocks

It is usually a very bad idea to have an empty catch block because when the exception occurs, nothing happens, and the program fails for unknown reasons.
 
In general, when a exception occurs, it can be thrown up to the caller, or it can be caught in a catch block. When catching an exception, some options include :
  • Inform the user (strongly recommended)
  • Log the problem, using the application specific loggers or JDK logging services, or similar tool
  • Send an email describing the problem to an administrator
Deciding what exactly to do seems to depend on the nature of the problem. If there is an actual bug in the program - a defect that needs to be fixed - then one might do all three of the above. In this case, the end user should likely be shown a generic "Sorry, we goofed" message, not a stack trace. It is usually considered bad form to display a stack trace to a non-technical end user, or if exposing a stack trace may be a security risk.

If the exception does not represent a bug, then different behavior may be appropriate. For example, if a problem with user input is detected and an exception is thrown as a result, then merely informing the user of the problem might be all that is required.

Exception translation

Occasionally, it is appropriate to translate one type of exception into another.

The data layer, for example, can profit from this technique. Here, the data layer seeks to hide almost all of its implementation details from other parts of the program. It even seeks to hide the basic persistence mechanism - whether or not a database or an ad hoc file scheme is used, for example.

However, every persistence style has specific exceptions - SQLException for databases,  and IOException for files, for example. If the rest of the program is to remain truly ignorant of the persistence mechanism, then these exceptions cannot be allowed to propagate outside the data layer, and must be translated into some higher level abstraction - DataAccessException, say.

Use template for repeated try-catch

Java's try-catch blocks are particularly common when using APIs which give an important role to checked exceptions (such as SQLException in JDBC). When using such an API, many published examples simply repeat the same try-catch code structure whenever necessary. However, it is simple to eliminate such code repetition using the template method pattern. The idea is to define the structure of the try-catch block in one place, in an abstract base class (ABC). Such an ABC is then extended whenever that particular try-catch block is needed. The concrete implementation of such an ABC will often have simple, "straight line" code.

Creating Thread-Safe Singleton?

posted 6 Feb 2012, 02:59 by Sanjeev Kumar   [ updated 16 Nov 2012, 10:45 ]


A singleton class should be designed to ensures that there exists only one instance per application. Special care must be taken if your application is deployed on a clustered environment as in this case it is possible that multiple instance of your singleton class are available in your application.  

Here are a few ways to create a thread safe singleton classes in your application.

1) Lazy loading Singleton instance - Using Synchronized method or block

public class SingletonClass{
    private SingletonClass sc;
    private SingletonClass(){}

    public static SingletonClass getInstance(){
        synchronized(SingletonClass.class) {
              if (sc == null) {
                  sc = new SingletonClass();
              } else {
                 return sc;
              }
        }
    }

}

Issues
- The use of synchronized keyword in a singleton class means that only one thread will be executing the synchronized block at a time and all other threads would be waiting.

2) Early initialization Singleton - Using Static Member Variable

public class SingletonClass{
    private static sc = new SingletonClass();
    private SingletonClass(){}

    public static SingletonClass getInstance(){
        return sc;
    }
}

This approach is also known as early initialization because we are creating the singleton instance at an early stage and not when the instance is actually needed by another class.

Issues
- The use of static member variable means that this singleton instance will be created as soon as the class is loaded by any Classloader in JVM. 

3) Singleton using Inner Classes

public class SingletonClass{
    private SingletonClass(){}
    private static class InstanceHolder{
        private static final SingletonClass INSTANCE = new SingletonClass();
    }
    public static SingletonClass getInstance(){
        return InstanceHolder.INSTANCE; //line1
    }
}

Here the instance is being created on demand and is also thread safe. The use of inner classes helps in the sense that the very first time singleton object is requested, the inner class is loaded by line1 and this loading of inner class causes the static member variable to be created and returned. Next time, the singleton member variable is requested causes the same static reference variable to be returned.

4) Singleton using enums

public enum Singleton{
    INSTANCE;
    private int a;
    public int getA() {
        return a;
    }
}

To get a single instance of this enum one should use:
Singleton.INSTANCE
To get the value of member variable a, one should use:
Singleton.INSTANCE.getA();

In my experience using enums is the best way to implement Singleton design pattern in any Java application. It is thread safe and also provides lazy initialization.

Hot tips on using Eclipse effectively

posted 29 Nov 2011, 08:30 by Sanjeev Kumar   [ updated 30 Nov 2011, 01:41 ]

Following are some tips that shall help you in avoiding potential issues and for being a little more productive while working with eclipse.

Avoid installation problems

Never install a new version of Eclipse on top of an older version. Rename the old one first to move it out of the way, and let the new version be unpacked in a clean directory.

Recovering your messed up workspace

Corrupted workspace is a common occurrence and troublemaker for many developers. So If your Eclipse installation has startup errors or a corrupted configuration, it might be time to get a fresh start. Start Eclipse with the –clean option, and all cached framework and runtime data will be cleared out. This often helps fix plug-in issues and improve general stability.

Increase the memory allocation

With new plugins getting added to the core eclipse functionality and the need to use additional third party plugins, the memory requirements for your eclipse workspace increases. The default memory allocation configured in eclipse is not enough for most J2ee development projects and that causes a sluggish response from you eclipse. If you get Out of Memory errors or sluggish response, you may have to increase the defaults that are set in eclipse.ini file in the Eclipse installation directory. In particular, if you get an error about “PermGen” memory (permanent generation), add this line at the end and restart Eclipse: -

XX:MaxPermSize=256m 

Use the lowest memory settings that work and perform well for your mix of projects.

Side by side editing

By dragging editors, you can show two files side by side. You can also edit two portions of the same file by using the Window > New Editor command.

Automatic code improvements

Set up Eclipse to automatically format source code and organize imports on every save. Select Window > Preferences > Java Editor > Save Actions to enable these actions. This dialog also lets you configure actions like removing unnecessary casts or adding missing annotations. Configuring your eclipse with optimized Compiler, Formatter and CheckStyle settings is described in detail in the post Using Eclipse Effectively

Keyboard shortcuts

It is productive and convenient to use keyboard shortcuts for performing certain tasks in eclipse rather than looking for options to do the same in various navigation menus. For example looking up references of a variable, method or a class can be quickly achieved via shortcut Ctrl+Shift+g. For your reference I have included a list of the most important keyboard shortcuts in my post Eclipse Keyboard Shortcuts

Other related posts

Java 7 Updates

posted 23 Nov 2011, 06:51 by Sanjeev Kumar   [ updated 24 Nov 2011, 03:31 ]

It has been quite sometime that Java 7 got released with plenty of new features and enhancements that shall interest Java developer community. Following sections of this page cover some of these changes with examples. 

Strings in switch statements

In the JDK 7 release, you can use a String object in the expression of a switch statement:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

The diamond operator "<>"

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();

Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List<String> list = new ArrayList<>();
list.add("A");
list.addAll(new ArrayList<>()); // Statement should fail since addAll expects Collection<? extends String>

In comparison, the following example compiles:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

Note: The diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.

Handling more than one type of exception

In Java SE 7 and later, a single catch block can handle more than one type of exception. Consider the following example, which contains duplicate code in each of the catch blocks:

//Prior to Java 7
catch (IOException ex) {
     logger.log(ex);
     throw ex;
catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.

The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

catch (IOException|SQLException ex) { // java 7 handling more than one type of exception
    logger.log(ex);
    throw ex;
}

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|). Some other advantages apart from syntactical improvement:
  • Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. 
  • A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers. 

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Re-throwing exceptions with more inclusive type checking

The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

Consider the following example:

  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws Exception {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }

This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.

However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:

  public void rethrowException(String exceptionName) throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }

This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:
  • The try block is able to throw it.
  • There are no other preceding catch blocks that can handle it.
  • It is a subtype or supertype of one of the catch clause's exception parameters.
The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.

In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of FirstException andSecondException.

The try-with-resources statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

// Java 7 Code
static String readFirstLineFromFile(String path) throws IOException { 
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }//no finally block required as resources will be closed automatically
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

//Before Java 7
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
    return br.readLine();
  } finally { 
    if (br != null) br.close();
  }
}

You may declare one or more resources in a try-with-resources statement.

Note: A try-with-resources statement can still have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Numeric literals with underscores

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

You can place underscores only between digits; you cannot place underscores in the following places:
  • At the beginning or end of a number
  • Adjacent to a decimal point in a floating point literal
  • Prior to an F or L suffix
  • In positions where a string of digits is expected
The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:

float pi1 = 3_.1415F;      // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F;      // Invalid; cannot put underscores adjacent to a decimal point
long ssn= 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix

int x1 = _52;              // This is an identifier, not a numeric literal
int x2 = 5_2;              // OK (decimal literal)
int x3 = 52_;              // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;        // OK (decimal literal)

int x5 = 0_x52;            // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;            // OK (hexadecimal literal)
int x8 = 0x52_;            // Invalid; cannot put underscores at the end of a number

int x9 = 0_52;             // OK (octal literal)
int x10 = 05_2;            // OK (octal literal)
int x11 = 052_;            // Invalid; cannot put underscores at the end of a number

Binary literals

In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals:

// An 8-bit 'byte' value:
byte aByte = (byte)0b00100001;

// A 16-bit 'short' value:
short aShort = (short)0b1010000101000101;

// Some 32-bit 'int' values:
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' value. Note the "L" suffix:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

Fork and Join

The effective use of parallel cores in a Java program has always been a challenge. There were few home-grown frameworks that would distribute the work across multiple cores and then join them to return the result set. Java 7 has incorporated this feature as a Fork and Join framework.

Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. It's like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers "steal" the work from those workers who are busy.

The core classes supporting the Fork-Join mechanism are ForkJoinPool and ForkJoinTask. The ForkJoinPool is basically a specialized implementation of ExecutorService implementing the work-stealing algorithm.

Supporting dynamism

Java is a statically typed language — the type checking of the variables, methods and return values is performed at compile time. The JVM executes this strongly-typed bytecode at runtime without having to worry about finding the type information.

There's another breed of typed languages — the dynamically typed languages. Ruby, Python and Clojure are in this category. The type information is unresolved until runtime in these languages. This is not possible in Java as it would not have any necessary type information.

There is an increasing pressure on Java folks improvise running the dynamic languages efficiently. Although it is possible to run these languages on a JVM (using Reflection), it's not without constraints and restrictions.

In Java 7, a new feature called invokedynamic was introduced. This makes VM changes to incorporate non-Java language requirements. A new package, java.lang.invoke, consisting of classes such as MethodHandle, CallSite and others, has been created to extend the support of dynamic languages.

Use PMD - Programming Mistake Detector?

posted 30 Oct 2011, 23:46 by Sanjeev Kumar   [ updated 19 Jan 2012, 09:00 ]

About PMD

How do you ensure that your code follows standard programming principles? For most Java development projects going on these days the answer would be to use "PMD". It is aiming towards becoming a de-facto tool for analyzing the source code and is being used by more and more Java applications everyday.

Note: There are a lot many tools that PMD competes with i.e Checkstyle, FindBugs, Hammurapi, Soot, Squale etc. However exploring capabilities of these tools(other than PMD) are out of scope of this article.

PMD is a static rule set based Java source code analyzer that identifies potential problems in the code like:
  1. Possible bugs - empty try/catch/finally/switch statements
  2. Dead code - unused local variables, parameters and private methods
  3. Suboptimal code - wasteful String/StringBuffer usage
  4. Overcomplicated expressions - unnecessary if statements, for loops that could be while loops
  5. Duplicate code - copied/pasted code means copied/pasted bugs
You can download everything from here, and you can get an overview of all the rules at the rulesets index page.

PMD is integrated with JDeveloper, Eclipse, JEdit, JBuilder, BlueJ, CodeGuide, NetBeans/Sun Java Studio Enterprise/Creator, IntelliJ IDEA, TextPad, Maven, Ant, Gel, JCreator, and Emacs.

Instructions for configuring PMD for Eclipse


Let me walk you through the steps required to quickly configure it with your Eclipse installation. It works like a breeze.
  1. Start Eclipse.
  2. Start the installation procedure : select the Help>Software Updates>Find and Install... menu item.
  3. Select "Search for new features to install" option and click Next.
  4. Click New Remote Site...
  5. Give a name (ie PMD Eclipse Site), enter the URL http://pmd.sourceforge.net/eclipse
  6. Select this new site in the Sites to include in search list and click Next.
  7. Select PMD for Eclipse 3 and Apache Xerces in the "Select the features to install" list and click Next.
  8. Accept the terms of the license agreements and click Next.
  9. Verify that the install location is your Eclipse installation directory, otherwise select the correct one, click Finish.
  10. A warning appear telling the feature is not signed. Ignore and click Install to continue.
  11. Accept to restart the workbench to load PMD into the workbench.
Eclipse is restarted and a PMD welcome page is displayed : the plugin is correctly installed. 

Writing custom rules (suggested by David Karr)

It is interesting and important to note that you can write your custom rules. Writing PMD rules is cool because you don't have to wait for PMD team to get around to implementing feature requests. Following are the two approaches to write custom rules.
  • Write a rule using Java
  • Write an XPath expression
More details about each of these approaches can be found at http://pmd.sourceforge.net/howtowritearule.html.


Happy coding..

Source

http://pmd.sourceforge.net/

Evolution of Java

posted 23 Oct 2011, 23:18 by Sanjeev Kumar   [ updated 29 Nov 2011, 23:20 ]

I thought it would be useful for architects, designers and developers to understand how Java has evolved since its inception so that they are aware of what all capabilities they have access to when working with a particular version of Java.  Besides, it is always good to have knowledge about evolution of the technologies that you are working with. 

Evolution of java

Choosing the right Collection

posted 23 Aug 2011, 03:41 by Sanjeev Kumar   [ updated 4 Apr 2012, 11:01 ]

Here is a quick guide for selecting the proper implementation of a Set, List, or Map in your application. 

The best general purpose or 'primary' implementations are likely ArrayList, LinkedHashMap, and LinkedHashSet. Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting.

Here, "ordering" refers to the order of items returned by an Iterator, and "sorting" refers to sorting items according to Comparable or Comparator.
 

Interface HasDuplicates? Implementations Historical
Set no HashSet ... LinkedHashSet* ... TreeSet
...
List yes ... ArrayList* ... LinkedList
...
Vector, Stack
Map no duplicate keys  HashMap ... LinkedHashMap* ... TreeMap Hashtable, Properties
Principal features of non-primary implementations :
  • HashMap has slightly better performance than LinkedHashMap
  • HashSet has slightly better performance than LinkedHashSet
  • TreeSet is ordered and sorted, but slow
  • TreeMap is ordered and sorted, but slow
  • LinkedList has fast adding to the start of the list, and fast deletion from the interior via iteration
Iteration order for above implementations :
  • HashSet - undefined
  • HashMap - undefined
  • LinkedHashSet - insertion order
  • LinkedHashMap - insertion order of keys (by default), or 'access order'
  • ArrayList - insertion order
  • LinkedList - insertion order
  • TreeSet - ascending order, according to Comparable / Comparator
  • TreeMap - ascending order of keys, according to Comparable / Comparator
For LinkedHashSet and LinkedHashMap, the re-insertion of an item does not affect insertion order.

While being used in a Map or Set, these items must not change state (hence, it is recommended that these items be immutable objects):

  • keys of a Map
  • items in a Set
Sorting requires either that : To retain the order of a ResultSet as specified in an ORDER BY clause, insert the records into a List or a LinkedHashMap.

Skip over certain classes when using Step Into(F5) in Eclipse’s debugger

posted 18 Aug 2011, 02:47 by Sanjeev Kumar   [ updated 11 Nov 2011, 05:59 ]

Whenever I use the Step Into feature (F5) in Eclipse’s debugger, I’m mainly interested in stepping through code in my own classes, not the ones from external libraries or even Java classes.

For example, there’s almost no reason to ever want to step into Spring’s code or proxy classes (other than to learn more about them or maybe debug a potential bug in Spring). And normally I’m not interested in Java util classes (eg. ArrayList). This also goes for Hibernate, Apache Commons, Google and many other external libraries.

Fortunately, Eclipse makes it easy to specify which classes to skip by allowing step filters. This makes it easier to focus on your own code and also keeps your editor area clean since Eclipse won’t be opening classes in separate editors all the time.

Enable Step Filters

To use step filters, the first step is to enable it. Eclipse comes with some default filters so let’s start by enabling them all. This will filter all Java classes (ie. java.*) and all Sun classes (ie. sun.*).

  1. Go to Window > Preferences > Java > Debug > Step Filtering.
  2. Select the option Use Step Filters.
  3. Click Select All to enable all the filters.
  4. Leave the other options below the filter list as-is.

Here’s an example of what it should look like:

NB: Even with step filters enabled, you can still set breakpoints within any of these classes (if you have the source) and Eclipse will still stop at the breakpoint. Step filtering only affects the way that Step Into works.

Also note that Eclipse will still step into your classes if they’re called from the ignored classes. For example, when you call Collections.sort(List, Comparator) and pass your own Comparator implementation, Eclipse will not step into the sort code, but it will step into your Comparator when it’s called by the sort code.

If you want to change this behaviour (ie. prevent Eclipse from stopping in your method), then deselect Step through filters. However, I’d recommend only doing this if you’ve tried out the default, because most times you’ll probably want to step through your own code.

The next step is to create some step filters of your own.

Creating your own step filters

Once you’ve enabled step filters, all you have to do is add the classes you want to filter. Let’s assume that we want to ignore all classes from Spring, especially proxy classes.

  1. If you’re not there already, go to Window > Preferences > Java > Debug > Step Filtering.
  2. Click Add Filter… A dialog should appear prompting you to enter a pattern.
  3. Enter a regular expression for the classes you want to filter in the Pattern to filter field then click Ok. In our example, enter org.springframework.* (see image below). It’s easier to specify the top level package name with an asterix at the end.
  4. Add another filter with the pattern $Proxy* to skip over Spring proxy classes (eg. when using Spring Transactions).
  5. Click Ok on the Preferences dialog when you’re done.

Here’s what the step filter pattern dialog should look like:

Now when you use the debugger, you won’t be taken into Spring classes when you use Step Into (F5).

Some ideas for custom filters

In addition to the Spring classes, you might also want to consider adding the following common libraries to your step filters to make debugging easier:

  • org.apache.*
  • org.hibernate.*
  • com.google.*
  • org.eclipse.*
  • org.osgi.*

The last two are especially useful if you’re doing Eclipse RCP and/or OSGi development.

Source : The article is republished from Eclipse On E

Awesome place to access Java source code online

posted 3 Aug 2011, 23:18 by Sanjeev Kumar   [ updated 10 Nov 2012, 11:23 ]

I thought it would be useful to have quick access to entire java source code and for those open source projects that you don't have the source for while developing our java based applications. I came across this awesome link while searching for java source code online and now I visit it almost everyday. You can browse fully cross-references java source code from Maven repository just like you do in your IDE. I found it very useful and recommend it to every Java developer.

http://www.mavenjava.com/

NOTE: A JavaGyan reader "Kallol Das" pointed out that the link above seems to be dead from quite some time. www.kickjava.com is another alternative but that too has availability issues at times.

1-10 of 26

Comments